在 SwiftUI 中使用此视图非常简单,只需 AttributedText(attributedString)
,与 Text
的简洁性非常相似。文本内容的宽度是受限的(高度会增长),并且是独立的(没有其他依赖项)。
这里有一个例子,展示了一些更精美的富文本以及内容如何
这段简化的代码仅包含用于测试目的的背景颜色和条形
let weirdText: NSAttributedString = {
let quote = "The quick brown fox jumps over the lazy 🐕."
let str = NSMutableAttributedString(string: quote)
str.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 20), range: NSRange(location: 4, length: 5))
str.addAttribute(.foregroundColor, value: UIColor.brown, range: NSRange(location: 10, length: 5))
str.addAttribute(.link, value: NSURL(string: "http://apple.com")!, range: NSRange(location: 16, length: 3))
str.addAttribute(.underlineStyle, value: 1, range: NSRange(location: 16, length: 3))
str.addAttribute(.baselineOffset, value: 4, range: NSRange(location: 26, length: 4))
return str
}()
var body: some View {
VStack {
//...
Color.blue.frame(height: 10)
HStack {
Color.red.frame(width: 10, height: 10)
AttributedText(weirdText)
.background(Color.green.opacity(0.5))
Color.red.frame(width: 150, height: 10)
}
Color.blue.frame(height: 10)
//...
}
}
该视图内部使用以下“层”:
AttributedText
仅为了其尺寸计算,通过 GeometryReader
和常用的 PreferenceKey
机制嵌入了 WrappedTextView
。WrappedTextView
是 SwiftUI 和 UIKit 之间的桥梁 UIViewRepresentable
。WrappedTextView
使用最终的 AttributedUITextView
来渲染富文本字符串。AttributedUITextView
是 UITextView
的一个子类。虽然此代码已在生产环境中使用,但它有一些缺点我想指出:
NSAttributedString
上的一个静态扩展来计算最终高度,这是根据 Apple 的示例代码,但在概念上与渲染文本的 UITextView 脱钩 - mehNSAttributedString
的问题 - 有其他库(例如 https://github.com/psharanda/Atributika)可以做到这一点。.foreground(Color.red)
)修改内容(因为我不知道如何将这些更改传播到 UIViewPresentable
- 如果您知道如何操作,请联系我)请以 PR 或电子邮件的形式报告任何反馈、错误、想法
omichde - Oliver Michalak - oliver@werk01.de
将其作为 SwiftPM 包嵌入:https://github.com/omichde/AttributedText
- 它应该在 iOS 13 及更高版本中工作...
AttributedText 在 MIT 许可证下可用
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.