swiftswiftui

Go to a new view using SwiftUI


I've got a basic view with a button using SwiftUI and I'm trying to present a new screen/view when the button is tapped. How do I do this? Am I suppose to create a delegate for this view that will tell the app's SceneDelegate to present a new view controller?

import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {
            Text("Hello World")
            Button(action: {
                //go to another view
            }) {
                Text("Do Something")
                    .font(.largeTitle)
                    .fontWeight(.ultraLight)
            }
        }
    }
}

Solution

  • The key is to use a NavigationView and a NavigationLink:

    import SwiftUI
    
    struct ContentView : View {
        var body: some View {
            NavigationView {
                VStack {
                    Text("Hello World")
                    NavigationLink(destination: DetailView()) {
                        Text("Do Something")
                    }
                }
            }
        }
    }