Skip to content

Instantly share code, notes, and snippets.

@lhoward
Last active October 31, 2020 22:42
Show Gist options
  • Select an option

  • Save lhoward/701b9b9ea5c3c0502b3f4f928d6f9217 to your computer and use it in GitHub Desktop.

Select an option

Save lhoward/701b9b9ea5c3c0502b3f4f928d6f9217 to your computer and use it in GitHub Desktop.
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