0

The issue

What I'm creating is a LazyVGrid with many UITextView as "cells" inside, but the text does not wrap when it exceeds the parent width.

When the text is a single line, all is fine:

Single line text

But when the text reaches the limit, something weird happens:

Multiline text

What I want to achieve is simply that the text wraps, can anyone help me?

The code

To have more flexibility, I chose to use a UIKit UITextView created using the UIViewRepresentable protocol, rather than using the new TextEditor provided by SwiftUI:

struct TextView: UIViewRepresentable {
    @Binding private var text: String

    init(text: Binding<String>) {
        self._text = text
    }

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.delegate = context.coordinator
        textView.isScrollEnabled = false
        textView.backgroundColor = .systemIndigo // debug
        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
        context.coordinator.parent = self
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
 
    // MARK: - Coordinator

    class Coordinator: NSObject, UITextViewDelegate {
        var parent: TextView
    
        init(_ parent: TextView) {
            self.parent = parent
        }
    
        func textViewDidChange(_ textView: UITextView) {
            parent.text = textView.text
        }
    }
}

This is my SwiftUI View:

struct ContentView: View {
    private let columns: [GridItem] = Array(repeating: .init(.flexible(), spacing: 0.0), count: 1)

    @ObservedObject private var viewModel: ContentViewModel

    init(viewModel: ContentViewModel) {
        self.viewModel = viewModel
    }

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach($viewModel.blocks) { $block in
                    TextView(text: $block.content)
                        .frame(minHeight: 24.0)
                }
            }
            .padding(.horizontal, 24.0)
        }
    }
}

I'll skip the ViewModel part because it's not relevant.

I've already seen and tried this Dynamic row hight containing TextEditor inside a List in SwiftUI, without success

Thanks everyone in advance ;)

Samuele Rizzo
  • 173
  • 1
  • 3
  • 8
  • Does this answer your question https://stackoverflow.com/a/62621521/12299030? – Asperi Jan 11 '22 at 08:56
  • Thanks @Asperi, but I already tried it without success. – Samuele Rizzo Jan 11 '22 at 09:08
  • Try this one https://stackoverflow.com/a/64966766/12299030. – Asperi Jan 11 '22 at 09:11
  • Thanks @Asperi, just tried it, and actually, the text no longer expands in width in that weird way but the height does not scale up properly. If I enable scrolling, the text wraps correctly but the UITextView height is always fixed. – Samuele Rizzo Jan 11 '22 at 09:58

0 Answers0