Last active
January 7, 2022 12:40
-
-
Save TerryCK/0d76b29a0d3b9bf8f4a46b7829ee4b46 to your computer and use it in GitHub Desktop.
a view stack in the enviroment by value semantic way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@main | |
struct MyApp: App { | |
// @State var viewStack: [ViewStack] = [] | |
var body: some Scene { | |
WindowGroup { | |
HomeView() | |
// .environment(\.viewStack, $viewStack) | |
} | |
} | |
} | |
enum ViewStack { | |
case scan, timePicker | |
} | |
struct ViewStackKey: EnvironmentKey { | |
static let defaultValue: Binding<[ViewStack]> = .constant([]) | |
} | |
extension EnvironmentValues { | |
var viewStack: Binding<[ViewStack]> { | |
get { self[ViewStackKey.self] } | |
set { self[ViewStackKey.self] = newValue } | |
} | |
} | |
struct PageView: View { | |
@State var viewStack: [ViewStack] = [] | |
let name: String | |
var body: some View { | |
VStack(spacing: 10) { | |
Text("currentPage: \(name)") | |
.padding() | |
Text("view stack count: \(viewStack.count)") | |
Button(action: { _ = viewStack.popLast() }) { | |
Text("back") | |
} | |
Button(action: { viewStack.append(.timePicker) }) { | |
Text("to timePicker") | |
} | |
Button(action: { viewStack.append(.scan) } ) { | |
Text("to scan") | |
} | |
} .environment(\.viewStack, $viewStack) | |
} | |
} | |
struct HomeView: View { | |
@Environment(\.viewStack) @Binding var viewStack | |
var body: some View { | |
switch viewStack.last { | |
case .scan: | |
PageView(name: "scan") | |
case .timePicker: | |
PageView(name: "timePicker") | |
default: | |
PageView(name: "Home") | |
} | |
} | |
} | |
struct HomeView_Previews: PreviewProvider { | |
static var previews: some View { | |
HomeView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment