Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presenting New Views in SwiftUI Without a Button

Tags:

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.

like image 678
BlueSpud Avatar asked Jun 05 '19 16:06

BlueSpud


People also ask

How do I hide the back button in SwiftUI?

The . navigationBarBackButtonHidden(true) will hide the back button.

How do I present a sheet in SwiftUI?

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(\.


1 Answers

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()         }     } } 
like image 126
Sada Avatar answered Oct 14 '22 11:10

Sada