6

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?

stardust4891
  • 2,390
  • 1
  • 18
  • 30
  • You can see my approach in the post [How do I create a multiline TextField in SwiftUI?](https://stackoverflow.com/questions/56471973/how-do-i-create-a-multiline-textfield-in-swiftui/58639072#58639072) – Asperi Nov 15 '19 at 14:48

1 Answers1

10

Try to perform modification asynchronously:

func textFieldDidChangeSelection(_ textField: UITextField) {
    DispatchQueue.main.async {
        self.parent.text = self.textField.text ?? ""
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • I ended up using the solution from your other comments. I just wanted to point out your solution the keyboard had a delay when closing a modal with the keyboard open in SwiftUI, so I tweaked it to this: https://justpaste.it/4dea0 – stardust4891 Nov 15 '19 at 17:51