如何在SwiftUI中将NSAttributedString与ScrollView一起使用?

问题描述 投票:2回答:1

我已经能够通过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

所以问题是,我们如何使UITextViewScrollView中工作?

swift uikit swiftui nsattributedstring
1个回答
1
投票

原因是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 !
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.