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:
But when the text reaches the limit, something weird happens:
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 ;)