Last active
October 31, 2020 22:42
-
-
Save lhoward/701b9b9ea5c3c0502b3f4f928d6f9217 to your computer and use it in GitHub Desktop.
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
| import SwiftUI | |
| final class NavigationManager: ObservableObject { | |
| var canPopToRootView: Bool // NB: this must not be @Published | |
| init() { | |
| self.canPopToRootView = true | |
| } | |
| } | |
| private struct PopToRootViewModifier<T>: ViewModifier { | |
| @EnvironmentObject private var navigationManager: NavigationManager | |
| @Binding var binding: T? | |
| let visibleAction: (() -> Void) | |
| init(ifVisible visibleAction: @escaping (() -> Void), | |
| elseReset binding: Binding<T?>) { | |
| self.visibleAction = visibleAction | |
| self._binding = binding | |
| } | |
| private func resetBinding() { | |
| if self.navigationManager.canPopToRootView { | |
| withAnimation(nil) { | |
| self.binding = nil | |
| } | |
| } | |
| } | |
| func body(content: Content) -> some View { | |
| content | |
| .onReselect(ifVisible: visibleAction, else: self.resetBinding) | |
| } | |
| } | |
| extension View { | |
| public func onReselect<T>(ifVisible visibleAction: @escaping (() -> Void), | |
| elseReset binding: Binding<T?>) -> some View { | |
| return self.modifier(PopToRootViewModifier(ifVisible: visibleAction, elseReset: binding)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment