I'm getting really close to implementing dynamic height for a UITextView in SwiftUI. Please help me work out these kinks:
- The UITextView has the correct height when it appears but does not adjust height as editing is being performed; I would like it to adjust.
- I'm receiving this in the console every time I edit the text in the TextView:
[SwiftUI] Modifying state during view update, this will cause undefined behavior.
Here's my code:
ItemEditView
TextView(text: $notes, textViewHeight: $textViewHeight)
.frame(height: self.textViewHeight)
UITextView
import SwiftUI
struct TextView: UIViewRepresentable {
@Binding var text: String
@Binding var textViewHeight: CGFloat
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = .systemFont(ofSize: 17)
textView.backgroundColor = .clear
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
textView.text = text
}
class Coordinator: NSObject, UITextViewDelegate {
var control: TextView
init(_ control: TextView) {
self.control = control
}
func textViewDidChange(_ textView: UITextView) {
control.text = textView.text
}
}
func makeCoordinator() -> TextView.Coordinator {
Coordinator(self)
}
}
Similar questions have been asked, but none of the solutions worked for me.
self.item
in my code, so I have no idea. – Shelby