Here is my code:
struct CustomTextField: UIViewRepresentable {
var placeholder: String
@Binding var text: String
func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
let uiView = UITextField()
uiView.delegate = context.coordinator
return uiView
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
uiView.placeholder = placeholder
uiView.text = text
if uiView.window != nil, !uiView.isFirstResponder {
uiView.becomeFirstResponder()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: CustomTextField
init(_ CustomTextField: CustomTextField) {
self.parent = CustomTextField
}
func textFieldDidChangeSelection(_ textField: UITextField) {
parent.text = textField.text ?? ""
}
}
}
Building doesn't cause the warning, but using CustomTextField
in the simulator does.
Here is the warning:
Modifying state during view update, this will cause undefined behavior.
It is showing on this line:
parent.text = textField.text ?? ""
How do I get rid of this warning? What am I doing wrong?
Try to perform modification asynchronously:
func textFieldDidChangeSelection(_ textField: UITextField) {
DispatchQueue.main.async {
self.parent.text = self.textField.text ?? ""
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With