Home>

Hello.
We would appreciate your help in using UITextField in SwiftUI.
I was able to describe up to displaying UITextField using UIViewRepresentable, but the initial value of the binding variable is not reflected in View, which is a problem.
How can I display "sample" in TextField when the View is displayed from the following source code?
Thanks for your professor.

Applicable source code
struct ContentView: View {
    @State var text = "sample"
    var body: some View {
        MyTextField("", text: $text)
    }
}

class MyTextFieldCoordinator: NSObject {
    var control: MyTextField
    init(_ control: MyTextField) {
        self.control = control
        super.init()
        control.textField.addTarget(self, action: #selector(textFieldEditingDidBegin(_:)), for: .editingDidBegin)
        control.textField.addTarget(self, action: #selector(textFieldEditingDidEnd(_:)), for: .editingDidEnd)
        control.textField.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged)
        control.textField.addTarget(self, action: #selector(textFieldEditingDidEndOnExit(_:)), for: .editingDidEndOnExit)
    }
    @objc private func textFieldEditingDidBegin(_ textField: UITextField) {
        control.onEditingChanged(true)
    }
    @objc private func textFieldEditingDidEnd(_ textField: UITextField) {
        control.onEditingChanged(false)
    }
    @objc private func textFieldEditingChanged(_ textField: UITextField) {
        control.text = textField.text ?? ""
    }
    @objc private func textFieldEditingDidEndOnExit(_ textField: UITextField) {
        control.onCommit()
    }
}
struct MyTextField: UIViewRepresentable {
    private let title: String?
    @Binding var text: String
    let onEditingChanged: (Bool) ->Void
    let onCommit: () ->Void
    let textField = UITextField()
    init(_ title: String?, text: Binding<String>, onEditingChanged: @escaping (Bool) ->Void = {_ in }, onCommit: @escaping () ->Void = {}) {
        self.title = title
        self._text = text
        self.onEditingChanged = onEditingChanged
        self.onCommit = onCommit
    }
    func makeCoordinator() ->MyTextFieldCoordinator {
        MyTextFieldCoordinator(self)
    }
    func makeUIView(context: Context) ->UITextField {
        textField.placeholder = title
        textField.delegate = context.coordinator as? UITextFieldDelegate
        return textField
    }
    func updateUIView(_ uiView: UITextField, context: Context) {
    }
}
Supplemental information (FW/tool ​​version, etc.)

Xcode version is 11.6.

  • Answer # 1

    solved.
    I was able to reflect the initial value by adding the following line to init of MyTextField.

    self.textField.text = text.wrappedValue