UITextView Representable in SwiftUI not respecting bounds for width in ScrollView
08:17 11 Apr 2021

I want to present text in a UITextView using SwiftUI. I'm using UIViewRepresentable and having issues with the width when it exceeds the bounds of the scrollView. I would like if to wrap the text but instead it just continues on one long line and the left and right are not visible:

enter image description here

This is my code:

struct ContentView: View {
    
    var messages = ["here is some long text to show the textView is not wrapping it's content"]
    
    var body: some View {
        GeometryReader { geometry in
            VStack(spacing: 0) {
                ScrollView(.vertical) {
                    ScrollViewReader { scrollView in
                        ZStack {
                            LazyVStack {
                                ForEach(messages, id: \.self) { message in
                                    TextView(text: message)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

struct TextView: UIViewRepresentable {
    
    var text: String
     
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
                
        textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
        textView.isScrollEnabled = false
        textView.backgroundColor = .clear
        textView.isEditable = false
        
        textView.clipsToBounds = true
        
        textView.isEditable = false
        
        textView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        textView.backgroundColor = #colorLiteral(red: 0.03137254902, green: 0.4980392157, blue: 0.9960784314, alpha: 1)
        textView.textColor = UIColor.white

        textView.text = text

        return textView
    }
 
    func updateUIView(_ uiView: UITextView, context: Context) {
        
    }
}

I'm wondering if this has something to do with the scrollView. And either way I would like to know if there is a fix to this? I tried setting the frame width to geometry.size.width but that did nothing.

swift xcode swiftui uitextview