NSAttributedStringBuilder
是一个易于使用的富文本字符串构建器,具有扩展的修饰符支持(粗体/斜体、图像、自定义间距等),支持大多数平台并且易于扩展。
您可以通过扩展 AttributedStringBuilding
来添加更多功能。所有 AttributedStringBuilding
的扩展都可用于符合该协议的 String
、NSAttributedString
、UIImage
和 NSImage
。
NSAttributedString.Key
AttributeContainer
)将以下内容添加到您的 Podfile
中以将 NSAttributedStringBuilder
集成到您的项目中
pod 'NSAttributedStringBuilder-jaeilers', '~> 0.3.0'
如果您使用 Xcode 管理依赖项,请选择您的项目,Package Dependencies 并通过输入 URL https://github.com/jaeilers/NSAttributedStringBuilder 添加包。
对于具有单独 Package.swift
的项目,请将依赖项添加到您的包清单中
dependencies: [
.package(url: "https://github.com/jaeilers/NSAttributedStringBuilder", .upToNextMajor(from: "0.3.0"))
]
您可以使用结果构建器或富文本字符串连接(+
运算符重载)来组合富文本字符串。 不需要额外的类型
let attributedString = NSAttributedString {
"Hello"
.font(.preferredFont(forTextStyle: .body))
.italic()
.foregroundColor(.green)
.underline()
Space()
"World"
.font(.preferredFont(forTextStyle: .headline))
.bold()
.foregroundColor(.orange)
.kerning(2.0)
.baselineOffset(-1)
}
// or
let attributedString = "Hello"
.font(.preferredFont(forTextStyle: .body))
.italic()
.foregroundColor(.green)
.underline()
+ Space()
+ "World"
.font(.preferredFont(forTextStyle: .headline))
.bold()
.foregroundColor(.orange)
.kerning(2.0)
.baselineOffset(-1)
以您喜欢的方式编写您的富文本字符串
let attributedString = NSAttributedString {
UIImage.checkmark.attributedString()
Space(.custom(1.0))
"The quick brown fox jumps over the lazy dog."
.attributedString()
Newline()
UIImage.add.attributedString()
}
// or
let attributedString = UIImage.checkmark
.space(.custom(1.0))
.text("The quick brown fox jumps over the lazy dog.")
.newline()
.image(UIImage.add)
您还可以从富文本字符串中单独配置和重用您的属性
let attributes = Attributes()
.font(.systemFont(ofSize: 16))
.italic()
.underline()
let attributedString = NSAttributedString {
"Hello"
.addingAttributes(attributes)
.foregroundColor(.systemBlue)
Space()
"World!"
.addingAttributes(attributes)
.foregroundColor(.systemTeal)
}
您可以通过扩展 AttributedStringBuilding
为缺少的属性添加您自己的修饰符或组合多个属性。 所有扩展都自动可用于符合该协议的所有类型 (UIImage/NSImage, String & NSAttributedString)。
添加扩展并非总是必要的。 如果您只想添加一个属性,请调用 addingAttribute(_:value:)
将属性添加到富文本字符串的整个范围。
public extension AttributedStringBuilding {
/// Combine multiple modifiers in one.
func linebreak(_ breakMode: NSLineBreakMode, strategy: NSParagraphStyle.LineBreakStrategy = .standard) -> NSAttributedString {
lineBreakMode(breakMode)
.lineBreakStrategy(strategy)
}
/// Add support for another modifier.
func accessibilityStrikethrough(_ hasStrikethrough: Bool) -> NSAttributedString {
addingAttribute(.accessibilityStrikethrough, value: NSNumber(value: hasStrikethrough))
}
}
本项目灵感来自 ethanhuang13/NSAttributedStringBuilder 和 svdo/swift-RichString。