警告
此仓库已被存档。
从 macOS 12+ / iOS 15+ / tvOS 15+ / watchOS 8+ 开始,您可以使用带有 SwiftUI
Text
视图的AttributedString
。
AttributedText 是一个 Swift 微型包,它通过包装 NSTextView
或 UITextView
(具体取决于平台)来提供在 SwiftUI 中渲染 NSAttributedString
的功能。
import AttributedText
import SwiftUI
struct ContentView: View {
var body: some View {
AttributedText {
let result = NSMutableAttributedString(
string: """
After the Big Bang
A brief summary of time
Life on earth
10 billion years
You reading this
13.7 billion years
"""
)
result.addAttributes(
[.font: UIFont.preferredFont(forTextStyle: .title1)],
range: NSRange(location: 0, length: 18)
)
result.addAttributes(
[.link: URL(string: "https://en.wikipedia.org/wiki/Big_Bang")!],
range: NSRange(location: 10, length: 8)
)
result.addAttributes(
[.font: UIFont.preferredFont(forTextStyle: .body)],
range: NSRange(location: 19, length: 23)
)
result.addAttributes(
[.font: UIFont.preferredFont(forTextStyle: .title2)],
range: NSRange(location: 43, length: 13)
)
result.addAttributes(
[.font: UIFont.preferredFont(forTextStyle: .body)],
range: NSRange(location: 57, length: 16)
)
result.addAttributes(
[.font: UIFont.preferredFont(forTextStyle: .title2)],
range: NSRange(location: 74, length: 16))
result.addAttributes(
[.font: UIFont.preferredFont(forTextStyle: .body)],
range: NSRange(location: 91, length: 18)
)
return result
}
.background(Color.gray.opacity(0.5))
.accentColor(.purple)
}
}
AttributedText
视图会占用所有可用宽度,并调整其高度以适应内容。
要更改文本对齐方式或换行模式,您需要向属性字符串添加一个 .paragraphStyle
属性。
您可以通过将其作为包依赖项添加到 Xcode 项目中,来添加 AttributedText。
https://github.com/gonzalezreal/AttributedText