这是我的代码:
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
会导致警告。
这是警告:
Modifying state during view update, this will cause undefined behavior.
它显示在这一行:
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/