Skip to content

Instantly share code, notes, and snippets.

@sunshinejr
Created February 26, 2020 10:57

Revisions

  1. sunshinejr created this gist Feb 26, 2020.
    37 changes: 37 additions & 0 deletions Navigation.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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()
    }