[英]How to control view state using an enum in SwiftUI
I apologize if this is a silly question, I am new to Swift and programming to boot.如果这是一个愚蠢的问题,我深表歉意,我是 Swift 的新手和编程启动。 I am trying to figure out how I can control my view state in SwiftUI using an enum.我想弄清楚如何使用枚举控制 SwiftUI 中的视图 state。 I am trying to keep my other view structs outside of ContentView
, but the problem is I cannot figure out how to write to currentView
to change its case outside of ContentView
.我试图将我的其他视图结构保留在ContentView
之外,但问题是我无法弄清楚如何写入currentView
以更改其在ContentView
之外的大小写。 For example, if I tap a button in StartView
, how can I affect the variable currentView
, which is in a different struct?例如,如果我在StartView
中点击一个按钮,我如何影响不同结构中的变量currentView
?
struct ContentView: View {
enum ViewType {
case start
case settings
case game
case finish
}
@State var currentView = ViewType.start
var body: some View {
Group {
if currentView == .start {
StartView()
} else if currentView == .settings {
SettingsView()
} else if currentView == .game {
GameView()
} else if currentView == .finish {
GameOverView()
}
}
}
}
struct StartView: View {
var body: some View {
Text("start")
Button(action: {
// How can I update my view state from within this struct?
}, label: {
Text("Button")
})
}
}
Any help or links to resources would be greatly appreciated.任何帮助或资源链接将不胜感激。
Thank you.谢谢。
As workingdog commented , just add @Binding
s inside each of your subviews:正如workingdog 评论的那样,只需在每个子视图中添加@Binding
:
struct StartView: View {
@Binding var currentView: ViewType
}
struct SettingsView: View {
@Binding var currentView: ViewType
}
struct GameView: View {
@Binding var currentView: ViewType
}
struct GameOverView: View {
@Binding var currentView: ViewType
}
Then, simply pass in the @State
to each of them.然后,只需将@State
传递给它们中的每一个。 All changes made in each subview's @Binding var currentView
will be synced to ContentView
's currentView
.在每个子视图的@Binding var currentView
中所做的所有更改都将同步到ContentView
的currentView
。
if currentView == .start {
StartView(currentView: $currentView)
} else if currentView == .settings {
SettingsView(currentView: $currentView)
} else if currentView == .game {
GameView(currentView: $currentView)
} else if currentView == .finish {
GameOverView(currentView: $currentView)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.