Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textFieldDidChangeSelection: Modifying state during view update, this will cause undefined behavior

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?

like image 632
stardust4891 Avatar asked Nov 15 '19 14:11

stardust4891


1 Answers

Try to perform modification asynchronously:

func textFieldDidChangeSelection(_ textField: UITextField) {
    DispatchQueue.main.async {
        self.parent.text = self.textField.text ?? ""
    }
}
like image 84
Asperi Avatar answered Oct 20 '22 21:10

Asperi