Is there anything wrong with this sample code? The Text
view updates with a one character delay. For example, if I type "123" in the textfield, the Text
view displays "12".
If I replace contacts
with a simple structure and change its givenName
property, then the view updates correctly.
Note that the print
statement does print correctly (ie, if you type "123" it prints "1" then "12" then "123". So the contacts.givenName
does get update as it should.
I have see other questions with a similar title, but this code does not seem to have the problems described in any of the questions that I have seen.
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)")
}
}
Update:
I added an id
to the Text view and increment it when I update the contact
state variable. It's not pretty but it works. Other solutions seem to be too involved fro something that shouldn't be this complicated.
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)
}
}