如何在 SwiftUI 中使用枚举控制视图状态

How to control view state using an enum in SwiftUI

如果这是一个愚蠢的问题,我深表歉意,我是 Swift 和编程的新手。我想弄清楚如何使用枚举在 SwiftUI 中控制我的视图状态。我试图将我的其他视图结构保留在 ContentView 之外,但问题是我无法弄清楚如何写入 currentView 以更改其在 ContentView 之外的大小写。例如,如果我点击 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")
        })
    }
}

任何帮助或资源链接将不胜感激。

谢谢。

作为 ,只需在每个子视图中添加 @Bindings:

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
}

然后,只需将 @State 传递给他们每个人。在每个子视图的 @Binding var currentView 中所做的所有更改将同步到 ContentViewcurrentView

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)
}