Apr 24, 2024 iOS

Show a new View from Button press Swift UI


To show a new view from a button press in SwiftUI, you typically use a navigation stack and navigation link. Here’s how you can achieve that:

import SwiftUI

struct ContentView: View {
    @State private var isShowingNewView = false
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Main View")
                
                // Button to navigate to the new view
                Button("Show New View") {
                    // Set the state to trigger navigation
                    isShowingNewView = true
                }
                
                // Navigation link to the new view
                NavigationLink(
                    destination: NewView(),
                    isActive: $isShowingNewView,
                    label: {
                        EmptyView()
                    })
                    .hidden()
            }
            .navigationTitle("Navigation Example")
        }
    }
}

struct NewView: View {
    var body: some View {
        Text("New View")
            .navigationTitle("New View")
    }
}

In this example:

  • We have a ContentView which is embedded in a NavigationView.
  • When the “Show New View” button is pressed, we set the isShowingNewView state variable to true.
  • This change in state triggers the NavigationLink to become active, navigating to the NewView.
  • The NewView contains the content for the new screen.
  • The navigationTitle modifier is used to set the title for each view.

This pattern allows you to navigate to a new view when a button is pressed in SwiftUI.