Loading...

How to open a second view from first view in iOS using SwiftUI?

question swiftui iOS
Ram Patra Published on April 2, 2024

In SwiftUI, you can open another view (or navigate to another view) on the click of a button by utilizing navigation views and navigation links. Here’s a basic example of how to achieve this:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Welcome to the first view!")
                
                // Button to navigate to the second view
                NavigationLink(destination: SecondView()) {
                    Text("Go to Second View")
                }
            }
            .navigationTitle("First View")
        }
    }
}

struct SecondView: View {
    var body: some View {
        VStack {
            Text("Welcome to the second view!")
        }
        .navigationTitle("Second View")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example:

  1. We have a ContentView which is wrapped inside a NavigationView.
  2. Inside ContentView, there’s a NavigationLink that triggers navigation to SecondView when clicked.
  3. The SecondView is a separate view containing its own content.

When you click the “Go to Second View” button in the ContentView, SwiftUI automatically handles navigation to the SecondView.

Make sure you import SwiftUI and add these views to your SwiftUI app’s view hierarchy accordingly. This is a simple example, and you can customize it further based on your app’s requirements.

Ram Patra Published on April 2, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui iOS April 2, 2024 How to force an app or a view to open in landscape only mode in iOS using SwiftUI?

In SwiftUI, you can force an app to open in landscape mode by configuring the supported interface orientations in your app’s target settings. Here’s a step-by-step guide to configuring interface orientations in Xcode:

question swiftui macos October 15, 2023 How to display the app version and build number in a macOS/iOS SwiftUI app?

To display both the app version and build number in a SwiftUI macOS/iOS app, you can use the Bundle class to access information from the app’s Info.plist file. The Info.plist file contains various details about your application, including its version and build number. Here’s how you can do it:

question swiftui March 6, 2023 How to render the icon on a menu bar as a template in SwiftUI?

Setting your app’s icon on the menu bar as a template makes it to adapt to light and dark modes automatically without you doing anything. To do this, you have to use this constructor of MenuBarExtra class.