Created
January 14, 2021 03:23
-
-
Save azamsharp/5e71767742f965e93e95fb1907602ccc 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
// | |
// 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