Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support programmatic view dismiss on iOS 15 and earlier versions

Tags:

ios

swift

swiftui

On iOS 14 and earlier, we import the presentationMode environment variable:

@Environment(\.presentationMode) var presentationMode

and then call self.presentationMode.wrappedValue.dismiss() to dismiss the view.

This has been deprecated on iOS 15, and a new environment variable, dismiss, is introduced:

@Environment(\.dismiss) var dismiss

which we can call directly using dismiss() to achieve the same.

I know we can do the following to call the appropriate dismiss function and support all versions:

if #available(iOS 15, *) {
    self.dismiss()
} else {
    self.presentationMode.wrappedValue.dismiss()
}

But how do I import/define the right environment variable? As trying this doesn't work:

if #available(iOS 15, *) {
    @Environment(\.dismiss) var dismiss
} else {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
}

Edit:

Apparently using presentationMode to dismiss a view in a Navigation stack still works on iOS 15 Beta 4. Unless there is a TabView inside the NavigationView:

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                NavigationLink(destination: ChildView()) {
                    Text("View Child")
                }
            }
        }
    }
}

struct ChildView: View {
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        Button(action: {
            print("Popping...")
            self.presentationMode.wrappedValue.dismiss()
        }, label: {
            Text("POP")
                .font(.headline)
        })
    }
}

presentatinMode doesn't work in this case.

like image 312
mota Avatar asked Nov 26 '22 22:11

mota


1 Answers

To support dismiss and iOS 14 add this extension to your EnvironmentValues

@available(iOS 14.0, *)
extension EnvironmentValues {
    var dismiss: () -> Void {
        { presentationMode.wrappedValue.dismiss() }
    }
}
like image 150
shbli Avatar answered Dec 09 '22 19:12

shbli