无法分配给属性:“ $ text”是不可变的

时间:2019-07-24 08:22:24

标签: swiftui

我想在SwiftUI中创建一个自定义文本字段来处理第一响应者,但是我在代码中遇到此错误,并且struct是不可变的,我不知道该怎么办?

struct CustomTextField: UIViewRepresentable {
class Coordinator: NSObject, UITextFieldDelegate {

    @Binding var text: String
    var didBecomeFirstResponder = false

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

    func textFieldDidChangeSelection(_ textField: UITextField) {
        text = textField.text ?? ""
    }

}

@Binding var text: String
var isFirstResponder: Bool = false

func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
    let textField = UITextField(frame: .zero)
    textField.delegate = context.coordinator
    return textField
}

func makeCoordinator() -> CustomTextField.Coordinator {
    return Coordinator(txt: $text)
}

func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
    uiView.text = text
    if isFirstResponder && !context.coordinator.didBecomeFirstResponder  {
        uiView.becomeFirstResponder()
        context.coordinator.didBecomeFirstResponder = true
    }
}
}

1 个答案:

答案 0 :(得分:6)

在beta 4中,属性包装器的实现发生了变化。

直到beta 3,这是有效的:

   self.$text = txt

在beta 4中,它更改为:

   self._text = txt

检查实现上的差异,在我发布的另一个问题中:

https://stackoverflow.com/a/57088052/7786555

有关更多详细信息:

https://stackoverflow.com/a/56975728/7786555