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:
- We have a
ContentView
which is wrapped inside aNavigationView
. - Inside
ContentView
, there’s aNavigationLink
that triggers navigation toSecondView
when clicked. - 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.