NSAttributedStringBuilder
使用 Flutter 风格语法组合 NSAttributedString
,由功能构建器提供动力。
项目链接: https://github.com/ethanhuang13/NSAttributedStringBuilder
特性
特性 | |
---|---|
使用 Swift 5.1 编写的开源库 | |
类似 SwiftUI 的语法 | |
支持 NSAttributedString.Key 中大部分属性 |
|
使用 Swift Package Manager 进行分发 | |
🧪 | 经过全面测试的代码 |
在 Swift 源兼容性测试套件 中持续集成 |
如何使用?
传统上我们这样组合 NSAttributedString
let mas = NSMutableAttributedString(string: "")
mas.append(NSAttributedString(string: "Hello world", attributes: [.font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.red]))
mas.append(NSAttributedString(string: "\n"))
mas.append(NSAttributedString(string: "with Swift", attributes: [.font: UIFont.systemFont(ofSize: 20), .foregroundColor: UIColor.orange]))
现在,使用 NSAttributedStringBuilder,我们可以用类似 SwiftUI 的语法来声明 NSAttributedString
let attributedString = NSAttributedString {
AText("Hello world")
.font(.systemFont(ofSize: 24))
.foregroundColor(.red)
LineBreak()
AText("with Swift")
.font(.systemFont(ofSize: 20))
.foregroundColor(.orange)
}
要求
Xcode 11。该项目使用 Swift 5.1 功能 Function Builder。
安装
Swift包
在Xcode 11中打开您的项目,导航到 菜单 -> Swift包 -> 添加包依赖 并输入 https://github.com/ethanhuang13/NSAttributedStringBuilder 进行安装。
CocoaPods
在您的Podfile
中添加 pod 'NSAttributedStringBuilder13'
。
SwiftUI示例项目
除了更清晰的NSAttributedString
语法外,由于NSAttributedStringBuilder使用函数构建器,它还使得可以在UIViewRepresentable
中构建组件(它将UIView
嵌入到SwiftUI的View
中)。
就像SwiftUI的Text
组件接受一个String
作为输入一样,样本项目中AttributedText
的作用是接收一个NSAttributedString
作为输入并在SwiftUI中渲染。
为了实现这一点,AttributedText.swift
使用@NSAttributedStringBuilder
支持类似SwiftUI的语法
在/SwiftUISampleApp/AttributedTextSample.xcodeproj中打开样本并检查AttributedText
。它使用UITextView
,您也可以使用UILabel
或NSTextView
。
待办事项
- 增强对图像附件的测试
已知问题
NSAttributedString
不支持链接颜色,因此具有.color()
修饰符的Link
组件没有任何效果。作为替代,您需要在UITextView.linkTextAttributes
或.tintColor
中指定。
其他
最初在Twitter 线程中讨论。一些代码灵感来源于 zonble