I have the following kind of code in a SwiftUI app.
And I want to perform a certain action (which is going to update my UI) when the state variable answerFlag has been touched (in the CustomButton view).
I would like to get some hints on the way to go for that.
My SwiftUI knowledge is still too limited or I do not yet master the use of what I know. The couple of things I tried did not work.
struct ContentView: View {
@State var answerFlag:Bool = false
......
var body: some View {
VStack {
Spacer()
CustomButton(text: answerText,
validAnswer: correctAnswer,
replyFlag: $answerFlag)
Spacer()
}.background(theBGColor)
.onTapGesture {
... do some useful thing ...
}
// I need to perform some action when answerFlag has changed !!??
}
}
struct CustomButton: View {
var text,validAnswer: String
@Binding var replyFlag:Bool
var body: some View {
Text(text)
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.primary)
.padding(.horizontal, 6.0)
.background(Color.brown)
.cornerRadius(5.0)
.overlay(RoundedRectangle(cornerRadius: 5.0)
.stroke(lineWidth: 2.0)
.foregroundColor(Color.gray))
.onTapGesture {
print("BUTTON-HIT:\(self.text)::\(self.validAnswer)")
if self.text == self.validAnswer {print("OK")}
else {print("NG")}
self.replyFlag = true
}
}
}
didSet. Look at this link and ctrl + f for "didSet" docs.swift.org/swift-book/LanguageGuide/Properties.html