I have a custom Text Field in SwiftUI, that adjusts the number of lines it has according to the amount of content in the text field. In the app, the user can add text fields, and so I'm storing the heights, and content of the text fields in arrays, and appending to the arrays as more text fields are added.
Whenever I remove the code inside the updateUIView()
, the app runs smoothly but of course, the text fields don't appear, but whenever I include it as in the code below, the CPU spikes to 99%, and the app freezes (even when there's only one text field).
Does anyone know why this is happening, and any fixes to it?
struct CustomMultilineTF: UIViewRepresentable {
@Binding var text: String
@Binding var height: CGFloat
var placeholder: String
func makeCoordinator() -> Coordinator {
return CustomMultilineTF.Coordinator(par: self)
}
func makeUIView(context: Context) -> UITextView {
let view = UITextView()
view.isEditable = true
view.isScrollEnabled = true
view.text = placeholder
view.font = .systemFont(ofSize: 18)
view.textColor = UIColor.gray
view.delegate = context.coordinator
view.backgroundColor = UIColor.gray.withAlphaComponent(0.05)
return view
}
func updateUIView(_ uiView: UITextView, context: Context) {
DispatchQueue.main.async {
self.height = uiView.contentSize.height
}
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: CustomMultilineTF
init(par: CustomMultilineTF) {
parent = par
}
func textViewDidBeginEditing(_ textView: UITextView) {
if self.parent.text == "" {
textView.text = ""
textView.textColor = .black
}
}
func textViewDidChange(_ textView: UITextView) {
DispatchQueue.main.async {
self.parent.height = textView.contentSize.height
self.parent.text = textView.text
}
}
}
}
question from:
https://stackoverflow.com/questions/65875850/swiftui-updateuiview-function-in-uiviewrepresentable-causes-app-to-freeze-and 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…