我非常接近在 SwiftUI 中为 UITextView 实现动态高度。请帮我解决这些问题:
- UITextView 在出现时具有正确的高度,但在执行编辑时不会调整高度;我想调整一下。
- 每次我在 TextView 中编辑文本时,我都会在控制台中收到此消息:
[SwiftUI] Modifying state during view update, this will cause undefined behavior.
这是我的代码:
项目编辑视图
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)
}
}
有人问过类似的问题,但没有一个解决方案对我有用。