BKAttributedStringBuilder
使用类似于 SwiftUI 语法的方式组合 NSAttributedString
,由当前提出的 函数构建器 驱动。
项目链接:https://github.com/codeswifter/BKAttributedStringBuilder
特性
特性 | |
---|---|
使用 Swift 5.0 编写的开源库 | |
类似 SwiftUI 语法,支持 if-else / ForEach | |
支持 NSAttributedString.Key 中大多数属性 |
|
使用 Swift Package Manager 进行分发 | |
完全测试的代码 |
如何使用?
传统上,我们这样组合 NSAttributedString
let mas = NSMutableAttributedString(string: "")
mas.append(NSAttributedString(string: "Hello", attributes: [
.foregroundColor: UIColor.red,
.backgroundColor: UIColor.yellow,
.font: UIFont.systemFont(ofSize: 20)
]))
mas.append(NSAttributedString(string: "\n"))
mas.append(NSAttributedString(string: "World", attributes: [
.font: UIFont.systemFont(ofSize: 40),
.paragraphStyle: {
let p = NSMutableParagraphStyle()
p.firstLineHeadIndent = 20
return p
}()
]))
// ...
现在,使用 BKAttributedStringBuilder,我们可以使用类似 SwiftUI 的语法来声明 NSAttributedString
let usingEnglish = false
label.attributedText = NSAttributedString {
"Hello".foregroundColor(.red)
.backgroundColor(.yellow)
.font(.systemFont(ofSize: 20))
"\n"
if usingEnglish {
"World".font(.systemFont(ofSize: 40))
.backgroundColor(.red)
.paragraphStyle {
let p = NSMutableParagraphStyle()
p.firstLineHeadIndent = 20
return p
}
} else {
"せかい".font(.systemFont(ofSize: 40))
.backgroundColor(.red)
}
"\n"
ForEach(1 ..< 5) {
"\($0)"
WhiteSpace(count: $0)
}
}
要求
需要 Xcode 14。该项目使用了 Swift 5.1 的功能 函数构建器。
安装
Swift Package
在Xcode 14中打开您的项目,导航到菜单 -> Swift Packages -> 添加包依赖,并输入https://github.com/codeswifter/BKAttributedStringBuilder进行安装。
示例应用
打开BKAttributedStringBuilder.xcworkspace并运行BKAttributedStringBuilderDemo_iOS
目标。
其他
部分代码受ethanhuang13启发。