Fitting a UITextView within a cell for a List, SwiftUI


Hi All,

I am having issues with a UITextView (I need this type of view so that it can detect links, email addresses, etc) that I created as a UIViewRepresentable. I am trying to fit this view inside a VStack that holds some other information that would be shown in a SwiftUI list view. It seems to fit fine vertically, but the width goes way out of frame. The text view's frame prints out as 3000 for the width. Any help is appreciated!

Code Block language
struct MessageTextView: UIViewRepresentable {
    @State var text = ""
    
    func makeUIView(context: Context) -> UITextView {
        let view = UITextView(frame: .zero)
        view.isScrollEnabled = false
        view.isEditable = false
        view.dataDetectorTypes = .all
        view.automaticallyAdjustsScrollIndicatorInsets = false
        view.font = UIFont.systemFont(ofSize: 12)
        return view
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
        uiView.font = UIFont.systemFont(ofSize: 12)
        print(uiView.frame.width)
    }
    
    typealias UIViewType = UITextView
}


Code Block language
    var body: some View {
        VStack(alignment: .leading, spacing: 8, content: {
            Text(message?.title ?? "")
                .fontWeight(.bold)
                .multilineTextAlignment(.leading)
            
            MessageTextView(text: message!.message)
            HStack {
                Text(message!.topicName)
                    .fontWeight(.bold)
                    .font(.caption)
                
                Spacer()
                
                Text("\(message!.creationDate)")
                    .font(.caption)
            }.padding([.bottom], 8)
        })
    }


Accepted Answer
UPDATE: This question has been resolved. I resolved it by converting a string to a NSAttributedString and using that string as the text in the UITextView by:

Code Block
textView.attributedText = self.yourTextValueHere

Inside the updateUIView function for the UITextView wrapper!


Fitting a UITextView within a cell for a List, SwiftUI
 
 
Q