这是我的代码:
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 ?? ""
我如何摆脱这个警告?我究竟做错了什么?
最佳答案
尝试异步执行修改:
func textFieldDidChangeSelection(_ textField: UITextField) {
DispatchQueue.main.async {
self.parent.text = self.textField.text ?? ""
}
}
关于ios - textFieldDidChangeSelection : Modifying state during view update,这将导致未定义的行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58878980/