这段示例代码有什么问题吗?Text
视图更新有一个字符的延迟。例如,如果在文本字段中输入 "123",Text
视图会显示 "12"。
如果我用一个简单的结构体替换 contacts
并改变它的 givenName
属性,那么视图就会正确更新。
请注意,print
语句确实打印正确(即,如果您键入 "123",它会先打印 "1",然后是 "12",最后是 "123")。因此,contacts.givenName
的确被更新了。
我看到其他问题的标题类似,但是这段代码似乎没有任何已知问题。
import SwiftUI
import Contacts
struct ContentView: View {
@State var name: String = ""
@State var contact = CNMutableContact()
var body: some View {
TextField("name", text: $name)
.onChange(of: name) { newValue in
contact.givenName = newValue
print("contact.givenName = \(contact.givenName)")
}
Text("contact.givenName = \(contact.givenName)")
}
}
更新: 我给 Text 视图添加了一个 id 属性,并在更新 contact 状态变量时对其进行了递增。虽然不太美观,但它可以工作。其他解决方案似乎对于本不应如此复杂的事情而言过于繁琐。
struct ContentView: View {
@State var name: String = ""
@State var contact = CNMutableContact()
@State var viewID = 0 // change this to foce the view to update
var body: some View {
TextField("name", text: $name)
.padding()
.onChange(of: name) { newValue in
contact.givenName = newValue
print("contact.givenName = \(contact.givenName)")
viewID += 1 // force the Text view to update
}
Text("contact.givenName = \(contact.givenName)").id(viewID)
}
}