使用 SwiftUI 风格的语法组合 NSAttributedString
,由 Result Builder 提供支持。
项目链接:https://github.com/ethanhuang13/NSAttributedStringBuilder
特性 | |
---|---|
🐦 | 用 Swift 5.4 编写的开源库 |
🍬 | 类似 SwiftUI 的语法 |
💪 | 支持 NSAttributedString.Key 中的大多数属性 |
📦 | 使用 Swift Package Manager 进行分发 |
🧪 | 经过充分测试的代码 |
🛠 | 持续集成在 Swift Source Compatibility Suite 中 |
传统上,我们像这样组合一个 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 12.5。该项目使用 Swift 5.4 的 Result Builder 特性。
在 Xcode 12 中打开您的项目,导航到 Menu -> Swift Packages -> Add Package Dependency 并输入 https://github.com/ethanhuang13/NSAttributedStringBuilder 进行安装。
将 pod 'NSAttributedStringBuilder13'
添加到您的 Podfile
。
除了更清晰的 NSAttributedString
语法之外,由于 NSAttributedStringBuilder 使用 Result Builder,它还支持在 UIViewRepresentable
(将 UIView
嵌入到 SwiftUI View
中)中构建组件的 API。
就像 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🙏。