AttributedStringStyle
博客文章
您可以在以下位置找到相关的博客文章 这里。
示例
要运行示例项目,请先克隆仓库,然后从 Example 目录中运行 pod install
要求
- iOS 9.0+
- Swift 4.2
安装
AttributedStringStyle 通过 CocoaPods 提供使用。要安装它,只需将以下行添加到 Podfile 中
pod 'AttributedStringStyle'
如何使用它
在您的应用程序中的任何位置定义一些抽象样式。例如。
enum Style {
case regular
case highlighted
}
一旦定义了样式,我们有两款工具可供使用
AttributedStringBuilder
,用于创建具有样式范围的富文本字符串AttributedStringStyler
定义每个样式的视觉属性
要创建富文本字符串并关注语义而不是显示,请按如下方式使用构建器
let content = "A simple string"
let builder = AttributedStringBuilder<Style>(string: content)
builder.setStyle(.regular)
let range = NSString(string: content).range(of: "simple")
builder.addStyle(.highlighted, range: range)
let semanticAttributedString = builder.build()
富文本字符串没有视觉属性,只有语义属性。
一旦定义了语义内容,您可以使用样式器创建具有视觉属性的新富文本字符串。
let styler = AttributedStringStyler<Style>()
styler.register(
attributes: [
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.gray
],
forStyle: .regular
)
styler.register(
attributes: [
.font: UIFont.boldSystemFont(ofSize: 14),
.foregroundColor: UIColor.black
],
forStyle: .highlighted
)
let visualAttributedString = semanticAttributedString.styled(with: styler)
这次结果是可视的。
作者
许可证
AttributedStringStyle在MIT许可证下可用。有关更多信息,请参阅LICENSE文件。