首页 > 解决方案 > 将状态/绑定传递给 UIViewRepresentable

问题描述

将状态变量传递给我的自定义文本字段的正确方法是什么?我希望避免其他方法/可观察的。这不应该工作吗?

我在示例项目中重新创建了以下问题。

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
    }
}

标签: iosswiftswift5

解决方案


以您的方式创建一个@Binding属性CustomTextField

struct CustomTextField: UIViewRepresentable {
    @Binding var text: String 
}

像这样初始化你的@Binding属性init()

init(text: Binding<String>) {
    self._text = text
}

text将属性传递给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请查看此答案


推荐阅读