SwiftUI UITextView wrapper how to size it content to match parent

Viewed 414

I have such UITextView wrapper and it works but when I place it inside List row. I would like it to autosize, i.e. have width that match parent in this case List Row VStack { }, and height that is autosize based on text length. Text should wrap. Now it nearly works but the longer text like a URL goes outside available row width.

List {
VStack(alignment: .leading) {
     if self.hasNote {
        TextView(text: text)

     }
}
struct TextView: UIViewRepresentable {

    // MARK: - Properties
    let text: String

    init(text: String) {
        self.text = text
    }

    func makeUIView(context: Context) -> UITextView {

        let textView = UITextView()
        //textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        textView.backgroundColor = UIColor.clear
        textView.isScrollEnabled = false
        textView.attributedText = self.attributedText
        textView.textContainer.lineBreakMode = .byWordWrapping
        //textView.layoutIfNeeded()
        textView.sizeToFit()
        return textView
    }

}

UPDATE

Now I have something like this it does fit parent SwiftUI views (rows in List) but instead it does not wrap text (or stretch vertically based on content size. If scrolled it wraps text correctly. Also if I set .frame(height: 500) I can see it wraps text. But it doesn't autosize correctly.

 func makeUIView(context: Context) -> UITextView {

        let textView = UITextView()

        textView.backgroundColor = UIColor.clear
        textView.isScrollEnabled = false
        textView.isSelectable = true

        let linkAttrs : [NSAttributedString.Key : Any]  = [
            .foregroundColor: accentColor,
            .underlineColor: accentColor,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]

        textView.linkTextAttributes = linkAttrs
        textView.attributedText = self.attributedText
        textView.textContainer.lineBreakMode = .byWordWrapping

        textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        textView.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
        textView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        textView.setContentHuggingPriority(.defaultLow, for: .vertical)
        textView.sizeToFit()

        return textView
    }
0 Answers
Related