Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable drag to dismiss in SwiftUI Modal

Tags:

swiftui

I've presented a modal view but I would like the user to go through some steps before it can be dismissed. Currently the view can be dragged to dismiss.

Is there a way to stop this from being possible?

I've watched the WWDC Session videos and they mention it but I can't seem to put my finger on the exact code I'd need.

struct OnboardingView2 : View {      @Binding     var dismissFlag: Bool      var body: some View {          VStack {             Text("Onboarding here! 🙌🏼")             Button(action: {                 self.dismissFlag.toggle()             }) {                 Text("Dismiss")             }         }     } } 

I currently have some text and a button I'm going to use at a later date to dismiss the view.

like image 506
Rob Peach Mellor Avatar asked Jun 11 '19 04:06

Rob Peach Mellor


Video Answer


2 Answers

iOS 15

Starting from iOS 15 we can use interactiveDismissDisabled:

func interactiveDismissDisabled(_ isDisabled: Bool = true) -> some View 

We just need to attach it to the sheet. Here is an example from the documentation:

struct PresentingView: View {     @Binding var showTerms: Bool      var body: some View {         AppContents()             .sheet(isPresented: $showTerms) {                 Sheet()             }     } }  struct Sheet: View {     @State private var acceptedTerms = false          var body: some View {         Form {             Button("Accept Terms") {                 acceptedTerms = true             }         }         .interactiveDismissDisabled(!acceptedTerms)     } } 
like image 129
pawello2222 Avatar answered Sep 25 '22 04:09

pawello2222


It is easy if you use the 3rd party lib Introspect, which is very useful as it access the corresponding UIKit component easily. In this case, the property in UIViewController:

VStack { ... } .introspectViewController {     $0.isModalInPresentation = true } 
like image 35
samwize Avatar answered Sep 25 '22 04:09

samwize