SwiftUI Как обновить свойство состояния, если оно было обновлено из представления листа
У меня есть текстовое поле, где вы можете ввести имя и кнопку для выбора из контактов, но когда я выбираю из контактов, текстовое поле не обновляется и выглядит пустым (и сохраняет пустой результат), но когда я нажимаю кнопку еще раз, он обновляет текстовое поле, как мне обновить текс-поле, как только лист закрывается
struct AddResultView: View {
@State var nameOfGame: String = ""
@State var opponentName: String = ""
@State var dateOfGame = Date()
@State var myScore: String = ""
@State var opponentScore: String = ""
@State var isOn: Bool = true
@ObservedObject var games = AllGames()
@Environment(\.presentationMode) var presentationMode
@ObservedObject var contactObj: ContactObject
var body: some View {
NavigationView {
Form {
Section {
TextField("Name of the game", text: $nameOfGame)
DatePicker("Pick date", selection: $dateOfGame, displayedComponents: .date)
HStack {
TextField("Enter opponent or choose from Contacts", text: $opponentName)
Button(action: {
self.contactObj.showContactPicker.toggle()
}) {
Image(systemName: "person.crop.circle.badge.plus").foregroundColor(.accentColor)}
}
.onReceive(self.contactObj.$cObj) { cObj in
self.opponentName = "\(self.contactObj.cObj.givenName) \(self.contactObj.cObj.familyName)"}
}
.sheet(isPresented: self.$contactObj.showContactPicker) {EmbeddedContactPicker(contactObj: self.contactObj)}
Section {
TextField("My Score", text: $myScore)
.keyboardType(.numberPad)
TextField("Opponent's Score", text: $opponentScore)
.keyboardType(.numberPad)
}.onTapGesture {
self.endEditing()
}
Section {
Toggle(isOn: $isOn) {
Text("Bigger score wins")
}
}
Button(action: {
self.saveNewResult()
self.presentationMode.wrappedValue.dismiss()
}){
Text("Submit")
}
.disabled(nameOfGame.isEmpty || opponentName.isEmpty || myScore.isEmpty || opponentScore.isEmpty)
}
.navigationBarTitle("Add New Result", displayMode: .inline)
.keyboardResponsive()
}
}
2 ответа
Если я правильно понял, снимок вашего кода contactObj
это ObservableObject
тогда решение может быть следующим
HStack {
TextField("Enter opponent or choose from Contacts", text: $opponentName)
Button(action: {
self.contactObj.showContactPicker.toggle()
}) {
Image(systemName: "person.crop.circle.badge.plus").foregroundColor(.accentColor)}
}
.onReceive(self.contactObj.$cObj) { cObj in // << here !!
// update name after it is changed in from picker
self.opponentName = "\(self.contactObj.cObj.givenName) \(self.contactObj.cObj.familyName)"
}
Text("\(self.contactObj.cObj.givenName) \(self.contactObj.cObj.familyName)")
}
.sheet(isPresented: self.$contactObj.showContactPicker) {EmbeddedContactPicker(contactObj: self.contactObj)}
Я понял!
.sheet(isPresented: self.$contactObj.showContactPicker, onDismiss:{self.opponentName = "\(self.contactObj.cObj.givenName) \(self.contactObj.cObj.familyName)"} ) {EmbeddedContactPicker(contactObj: self.contactObj)}