How to control view state using an enum in SwiftUI

Viewed 374

I apologize if this is a silly question, I am new to Swift and programming to boot. I am trying to figure out how I can control my view state in SwiftUI using an enum. 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. For example, if I tap a button in StartView, how can I affect the variable currentView, which is in a different struct?

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.

1 Answers

As workingdog commented, just add @Bindings inside each of your subviews:

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. All changes made in each subview's @Binding var currentView will be synced to ContentView's 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)
}
Related