Home > Software engineering >  Warning: "Modifying state during view update, this will cause undefined behavior." in UIVi
Warning: "Modifying state during view update, this will cause undefined behavior." in UIVi

Time:04-19

So I have a UIViewRepresentable which wraps a UITextField, and I get this error during the textFieldshouldChangeCharactersInRange method:

struct MyTextField: UIViewRepresentable {

    class Coordinator: NSObject, UITextFieldDelegate, ObservableObject {
    
        @Binding var text: String

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if let currentValue = textField.text as NSString? {
                let proposedValue = currentValue.replacingCharacters(in: range, with: string)
                text = proposedValue // Warning is thrown from here
            }
            return true
        }
    }
...

What's the correct way to update the binding here without triggering this warning?

CodePudding user response:

Update on next even loop, like

DispatchQueue.main.async {
    text = proposedValue
}
  • Related