我已经能够通过NSAttributedString
渲染UIViewRepresentable
,这在将视图包装到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)
}
}
Edit:我尝试使用设置了UITextView
属性而不是text
属性的包装的attributeText
,但这也无法在ScrollView
中呈现,因此问题似乎出在UITextView
,而不是NSAttributedString
。
所以问题是,我们如何使UITextView
在ScrollView
中工作?
原因是SwiftUI ScrollView
需要定义的内容大小,但使用的UITextView
本身是UIScrollView
,并根据父视图中的可用空间来检测内容。因此,它发生了不确定大小的循环。
这里是如何解决此问题的可能方法的简化演示。这个想法是计算UITextView
的内容大小并将其传递给SwiftUI ...
struct TextWithAttributedString: UIViewRepresentable {
@Binding var height: CGFloat
var attributedString: NSAttributedString
func makeUIView(context: Context) -> UITextView {
let textView = UITextView(frame: .zero)
textView.isEditable = false
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
textView.attributedText = self.attributedString
// calculate height based on main screen, but this might be
// improved for more generic cases
height = textView.sizeThatFits(UIScreen.main.bounds.size).height
}
}
struct NSAttributedStringView: View {
@State private var textHeight: CGFloat = .zero
var body: some View {
ScrollView {
TextWithAttributedString(height: $textHeight, attributedString: NSAttributedString(string: exampleText))
.frame(height: textHeight) // << specify height explicitly !
}
}
}