gpt4 book ai didi

ios - textFieldDidChangeSelection : Modifying state during view update, 这将导致未定义的行为

转载 作者:行者123 更新时间:2023-11-29 05:18:52 25 4
gpt4 key购买 nike

这是我的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com