将状态变量传递给我的自定义文本字段的正确方法是什么?我希望避免其他方法/可观察的。这不应该工作吗?
我在示例项目中重新创建了以下问题。
import SwiftUI
struct ParentView: View {
@State var text: String = "initial"
var body: some View {
VStack {
ChildView(text: $text)
Text(self.text)
}
}
}
struct ChildView: View {
@Binding var text: String
var body: some View {
MyTextField(text: $text).frame(width: 300, height: 40, alignment: .center)
}
}
struct MyTextField: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextField {
let view = UITextField()
view.borderStyle = UITextField.BorderStyle.roundedRect
return view
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
}
最佳答案
创建 @Binding
您的 CustomTextField
中的属性(property)像:
struct CustomTextField: UIViewRepresentable {
@Binding var text: String
}
初始化您的
@Binding
位于 init()
的属性(property)像:init(text: Binding<String>) {
self._text = text
}
通过
text
属性(property)给 UITextField
像:func makeUIView(context: Context) -> UITextField {
// Customise the TextField as you wish
textField.text = text
return textField
}
更新
text
的 UITextField
像:func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = self.text
}
更新
@Binding
带有用户输入文本的属性,例如: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.text = proposedValue as String // Here is updating
}
return true
}
您的
ContentView
应该看起来像:struct ContentView: View {
@State var text: String = ""
var body: some View {
CustomTextField(text: $text)
}
}
现在好了,如果你想要
CustomTextField
的完整代码然后看this answer .
关于ios - 将状态/绑定(bind)传递给 UIViewRepresentable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61446026/