NSAttributedStringBuilder
NSAttributedStringBuilder
是一个易于使用的属性字符串构建器,具有扩展修改器支持(粗体/斜体、图片、自定义间距等),支持大多数平台,并且可以轻松扩展。
通过扩展 AttributedStringBuilding
来添加更多功能。所有 AttributedStringBuilding
的扩展都适用于符合该协议的 String
、NSAttributedString
、UIImage
和 NSImage
。
特性
- 支持大部分
NSAttributedString.Key
- 灵活的字符串、图片等的组合
- 声明性语法
- SwiftUI 兼容
- 完全由单元测试覆盖
安装
CocoaPods
将以下内容添加到你的 Podfile
中,以便将 NSAttributedStringBuilder
集成到你的项目中
pod 'NSAttributedStringBuilder-jaeilers', '~> 0.2.0'
Swift 软件包管理器
如果你使用 Xcode 来管理依赖,选择你的项目,软件包依赖,并通过输入 URL https://github.com/jaeilers/NSAttributedStringBuilder 来添加软件包。
对于具有单独的 Package.swift
的项目,将依赖项添加到你的包清单中
dependencies: [
.package(url: "https://github.com/jaeilers/NSAttributedStringBuilder", .upToNextMajor(from: "0.2.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)
如何添加自定义修改符
你可以通过扩展 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。