这是我的代码:
struct CustomTextField: UIViewRepresentable {
var placeholder: String
@Binding var text: String
func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
let uiView = UITextField()
uiView.delegate = context.coordinator
return uiView
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
uiView.placeholder = placeholder
uiView.text = text
if uiView.window != nil, !uiView.isFirstResponder {
uiView.becomeFirstResponder()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: CustomTextField
init(_ CustomTextField: CustomTextField) {
self.parent = CustomTextField
}
func textFieldDidChangeSelection(_ textField: UITextField) {
parent.text = textField.text ?? ""
}
}
}
构建不会引起警告,但是在模拟器中使用CustomTextField
会引起警告。
这是警告:
在视图更新期间修改状态,这将导致未定义的行为。
它显示在这一行:
parent.text = textField.text ?? ""
如何摆脱此警告?我在做什么错了?
答案 0 :(得分:0)
尝试异步执行修改:
func textFieldDidChangeSelection(_ textField: UITextField) {
DispatchQueue.main.async {
parent.text = textField.text ?? ""
}
}