[英]Action based on a variable update in SwiftUI
I have the following kind of code in a SwiftUI
app.我在SwiftUI
应用程序中有以下类型的代码。
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).当 state 变量answerFlag被触摸时(在CustomButton视图中),我想执行某个操作(这将更新我的 UI)。
I would like to get some hints on the way to go for that.为此,我想在前往 go 的路上获得一些提示。
My SwiftUI
knowledge is still too limited or I do not yet master the use of what I know. SwiftUI
我的知识还是太有限了,或者我还没有掌握我所知道的用途。 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
}
}
}
Here is possible way...这是可能的方法......
SwiftUI 2.0 SwiftUI 2.0
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 !!??
.onChange(of: answerFlag) { newValue in
// ... do anything heeded here
}
}
SwiftUI 1.0+ SwiftUI 1.0+
Similarly to above add to some view the following与上面类似,添加一些查看以下内容
import Combine
...
.onReceive(Just(answerFlag)) { newValue in
// ... do anything heeded here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.