Skip to content

Instantly share code, notes, and snippets.

@zats
Last active November 18, 2023 02:27
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 zats/818bf4d73d99077fb08f82c20d208d16 to your computer and use it in GitHub Desktop.
Save zats/818bf4d73d99077fb08f82c20d208d16 to your computer and use it in GitHub Desktop.
enum AppNavigationTarget: Hashable {
case related(to: Post, showOriginal: Bool, postType: PostType)
case showPost(parentId: String, showRealted: Bool, postType: PostType)
case user(User, sort: FeedType.UserSort, postType: PostType)
case search(String, postType: PostType, searchType: SearchType)
case favorites(sort: FeedType.FavoritesSort, postType: PostType)
case follows(sort: FeedType.FollowsSort, postType: PostType)
case community(sort: FeedType.CommunitySort, postType: PostType)
}
// ...
Button("Submit") {
navigationController.navigate(to: .search(searchText, postType: .all, searchType: .advanced))
}
// ...
final class NavigationController: ObservableObject {
@Published var path = NavigationPath()
init(initialValue: AppNavigationTarget? = nil) {
if let initialValue {
path.append(initialValue)
}
}
func popToRoot() {
path.removeLast(path.count)
}
var isEmpty: Bool {
path.isEmpty
}
func navigate(to target: AppNavigationTarget) {
path.append(target)
objectWillChange.send()
}
}
struct RootView: View {
// ...
@ObservedObject var navigationController = NavigationController()
var body: View {
NavigationStack(path: $navigationController.path) {
InitialView()
.navigationDestination(for: AppNavigationTarget.self) { target in
switch target {
case let .related(toPost, showOriginal, postType):
RelatedView(
post: toPost,
showOriginal: showOriginal,
postType: postType,
navigationController: navigationController
)
// ....
// navigationController can also be an Environment set variable
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment