Skip to content

Instantly share code, notes, and snippets.

@sunshinejr
Created February 26, 2020 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunshinejr/fdce4423aad68f95d90595f8fa1eaf7b to your computer and use it in GitHub Desktop.
Save sunshinejr/fdce4423aad68f95d90595f8fa1eaf7b to your computer and use it in GitHub Desktop.
SwiftUI Navigation stack
struct NavigationStack: View {
@ObservedObject var viewModel: NavigationStackViewModel
var body: some View {
viewModel.currentBody?
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
}
}
final class NavigationStackViewModel: Navigation, ObservableObject {
@Published private var stack = [AnyView]()
@Published var currentBody: AnyView?
init(root: AnyView? = nil) {
currentBody = root
}
func present<T: View>(view newView: T) {
if let currentBody = currentBody {
stack.append(currentBody)
}
currentBody = AnyView(newView)
}
func dismiss() {
currentBody = stack.removeLast()
}
}
protocol Navigation {
var currentBody: AnyView? { get }
func present<T: View>(view: T)
func dismiss()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment