NavigationLink (switch between views) in SwiftUI

Dec 26, 2020 1 min read
NavigationLink (switch between views) in SwiftUI

There are many ways to interact with different screens (views), here I'll cover them all with examples and pictures. Simple and concise.

Updated for SwiftUI 2.0

Demo


We can do the above with the following code:

If you want to have the "Go Back" button removed, add  .navigationBarBackButtonHidden(true)

ContentView

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: SecondView()) {
                    Text("Second View")
                }
             }
            .hideNavigationBar()
        }
    }
}


SecondView

import SwiftUI

struct SecondView: View {
    var body: some View {
        VStack {
            Text("You are in View 2 ✅")
        }
        .navigationBarBackButtonHidden(true)
    }
}

Extension

import SwiftUI

struct HiddenNavigationBar: ViewModifier {
    init() {
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
        UINavigationBar.appearance().shadowImage = UIImage()
    }
    
    func body(content: Content) -> some View {
        content
            .navigationBarTitle("Back", displayMode: .inline)
            .navigationBarHidden(true)
    }
}

extension View {
    func hideNavigationBar() -> some View {
        modifier( HiddenNavigationBar() )
    }
}
Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.