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
ContentViewwhich is embedded in aNavigationView. - When the “Show New View” button is pressed, we set the
isShowingNewViewstate variable totrue. - This change in state triggers the
NavigationLinkto become active, navigating to theNewView. - The
NewViewcontains the content for the new screen. - The
navigationTitlemodifier 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.