'Binding not working in UIViewRepresantable
I am trying to make a custom textfield using UIViewRepresantable but when I enter value in textfield, it is not reflecting in the root @State variable:
struct UiKitTextField: UIViewRepresentable {
@Binding var amount: Double
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var amount: Double
init(amount: Binding<Double>) {
self._amount = amount
}
}
func makeUIView(context: Context) -> UITextField {
let textField = UITextField(frame: .zero)
textField.delegate = context.coordinator
return textField
}
func makeCoordinator() -> Coordinator {
return Coordinator(amount: $amount)
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = "\(amount)"
}
typealias UIViewType = UITextField
}
Solution 1:[1]
You need to implement Delegate with Cordinator to update value
struct UiKitTextField: UIViewRepresentable {
@Binding var amount: Double
class Coordinator: NSObject, UITextFieldDelegate {
var parent: UiKitTextField
init(_ parent: UiKitTextField) {
self.parent = parent
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let value = textField.text as NSString? {
let proposedValue = value.replacingCharacters(in: range, with: string)
parent.amount = Double(proposedValue as String) ?? 0 // Here is updating
}
return true
}
}
func makeUIView(context: Context) -> UITextField {
let textField = UITextField(frame: .zero)
textField.delegate = context.coordinator
return textField
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = "\(amount)"
}
typealias UIViewType = UITextField
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Toseef Khilji |
