Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created January 14, 2021 03:23
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 azamsharp/5e71767742f965e93e95fb1907602ccc to your computer and use it in GitHub Desktop.
Save azamsharp/5e71767742f965e93e95fb1907602ccc to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// RoutingDemo
//
// Created by Mohammad Azam on 1/13/21.
//
import SwiftUI
extension View {
func toAnyView() -> AnyView {
return AnyView(self)
}
}
enum Route {
case detail(String)
case aboutUs
case addCountry
}
class Navigator {
static func navigate<T: View>(_ route: Route, content: () -> T) -> AnyView {
switch route {
case .detail(let country):
return
NavigationLink(
destination: DetailView(country: country)) {
content()
}.toAnyView()
case .aboutUs:
return Text("About Us").toAnyView()
case .addCountry:
return Text("Add Country").toAnyView()
}
}
}
struct ContentView: View {
let countries = ["Pakistan", "United States", "Canada", "Iceland", "Thailand", "England", "Australia"]
var body: some View {
NavigationView {
VStack {
Button(action: {}, label: {
Navigator.navigate(.detail("USA"), content: {
Text("GO")
})
})
List(countries, id: \.self) { country in
Navigator.navigate(.detail(country), content: {
Text(country)
})
}.listStyle(PlainListStyle())
.navigationTitle("Countries")
}
}
}
}
struct DetailView: View {
let country: String
var body: some View {
Text(country)
.font(.largeTitle)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment