Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS SwiftUI: pop or dismiss view programmatically

Tags:

ios

swift

swiftui

I couldn't find any reference about any ways to make a pop or a dismiss programmatically of my presented view with SwiftUI.

Seems to me that the only way is to use the already integrated slide dow action for the modal(and what/how if I want to disable this feature?), and the back button for the navigation stack.

Does anyone know a solution? Do you know if this is a bug or it will stays like this?

like image 580
Andrea Miotto Avatar asked Jun 09 '19 09:06

Andrea Miotto


People also ask

How do I dismiss a SwiftUI view?

The first option is to tell the view to dismiss itself using its presentation mode environment key. Any view can read its presentation mode using @Environment(\. presentationMode) , and calling wrappedValue. dismiss() on that will cause the view to be dismissed.

Is there a Viewdidload in SwiftUI?

SwiftUI gives us equivalents to UIKit's viewDidAppear() and viewDidDisappear() in the form of onAppear() and onDisappear() . You can attach any code to these two events that you want, and SwiftUI will execute them when they occur.


2 Answers

This example uses the new environment var documented in the Beta 5 Release Notes, which was using a value property. It was changed in a later beta to use a wrappedValue property. This example is now current for the GM version. This exact same concept works to dismiss Modal views presented with the .sheet modifier.

import SwiftUI  struct DetailView: View {     @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>     var body: some View {         Button(             "Here is Detail View. Tap to go back.",             action: { self.presentationMode.wrappedValue.dismiss() }         )     } }  struct RootView: View {     var body: some View {         VStack {             NavigationLink(destination: DetailView())             { Text("I am Root. Tap for Detail View.") }         }     } }  struct ContentView: View {     var body: some View {         NavigationView {             RootView()         }     } } 
like image 70
Chuck H Avatar answered Oct 15 '22 19:10

Chuck H


SwiftUI Xcode Beta 5

First, declare the @Environment which has a dismiss method which you can use anywhere to dismiss the view.

import SwiftUI  struct GameView: View {          @Environment(\.presentationMode) var presentation          var body: some View {         Button("Done") {             self.presentation.wrappedValue.dismiss()         }     } } 
like image 34
Prashant Gaikwad Avatar answered Oct 15 '22 18:10

Prashant Gaikwad