【发布时间】:2020-01-24 00:43:04
【问题描述】:
我已经能够通过UIViewRepresentable 渲染NSAttributedStrings,在我将视图包裹在ScrollView 之前效果很好。
当放置在ScrollView 内时,NSAttributedString 视图会停止渲染。
我尝试了一些其他方法,将NSAttributedString 替换为将多个Text() 视图一起添加以获取在ScrollView 内工作并支持斜体 和monospace font 的格式。不幸的是,这不适用于文本块内的links,这意味着我仍然需要NSAttributedString。
import SwiftUI
struct TextWithAttributedString: UIViewRepresentable {
var attributedString: NSAttributedString
init(_ attributedString: NSAttributedString) {
self.attributedString = attributedString
}
func makeUIView(context: Context) -> UITextView {
let textView = UITextView(frame: .zero)
textView.attributedText = self.attributedString
textView.isEditable = false
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
textView.attributedText = self.attributedString
}
}
let exampleText = """
Fugiat id blanditiis et est culpa voluptas. Vivamus aliquet enim eu blandit blandit. Sit eget praesentium maxime sit molestiae et alias aut.
"""
struct NSAttributedStringView: View {
var body: some View {
// Note: when uncommented, the view breaks
// ScrollView {
TextWithAttributedString(NSAttributedString(string: exampleText))
// }
}
}
struct NSAttributedStringView_Previews: PreviewProvider {
static var previews: some View {
NSAttributedStringView()
.previewLayout(.sizeThatFits)
}
}
编辑:我尝试使用包装的UITextView 和text 属性集而不是attributeText 属性,但这也无法在ScrollView 中呈现,所以问题似乎是UITextView,而不是NSAttributedString。
所以问题是,我们如何让UITextView 在ScrollView 中工作?
【问题讨论】:
标签: swift uikit swiftui nsattributedstring