So I want to present a new view using SwiftUI, without the user having to tap a button, since NavigationButton
would work with that. Here is an example
struct ContentView : View { var model: Model var body: some View { NavigationView { Text("Hello World") }.onAppear { if model.shouldPresent { // present a new view } } } }
In the onAppear
I want to include some code that will push a new view onto the navigation stack.
The . navigationBarBackButtonHidden(true) will hide the back button.
To use a sheet, give it something to show (some text, an image, a custom view, etc), add a Boolean that defines whether the detail view should be showing, then attach it to your main view as a modal sheet. Important: If you're targeting iOS 14 or below, you should use @Environment(\.
Here's a way to present view as a Modal.
struct PresentOnloadView: View { var body: some View { HStack { Text("Hey there") } .presentation(Modal(HelloView(), onDismiss: nil)) } } struct HelloView: View { var body: some View { Text("Whats up! 👻") } }
Similarly, if you're looking to control whether to present or not using a variable, you can do something like this..
struct PresentOnloadControlledView : View { @State var sayHello = false var body: some View { HStack { Text("What's up!") } .onAppear(perform: { // Decide whether to show another view or not here self.sayHello = true }) .presentation(sayHello ? Modal(HelloView()) : nil) } }
As of Version 11.0 beta 4 ➝ .presentation and Modal has been deprecated.
Not to worry! .sheet saves the day!
struct PresentOnloadControlledView : View { @State var sayHello = false var body: some View { HStack { Text("What's up!") } .onAppear(perform: { // Decide whether to show another view or not here self.sayHello = true }) .sheet(isPresented: $sayHello) { HelloView() } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With