Azhagusundaram Tamil
Azhagusundaram Tamil

Reputation: 2411

Restrict sheet dismissing by swipe down in swiftui

I have a button and when I click on it a new View will present as a sheet. In SwiftUI by default swipe down gesture will dismiss the sheet view. I want to restrict it.

I'll have a button for dismissing. Until I press that button sheet should not get dismissed.

Upvotes: 8

Views: 6622

Answers (4)

Imanou Petit
Imanou Petit

Reputation: 92589

Beginning with iOS 15, SwiftUI provides the interactiveDismissDisabled(_:) modifier, which allows you to disable the interactive dismissal of sheets.

Here's an example of how to use it:

import SwiftUI

struct ContentView: View {
    @State var isPresentingSettings = false

    var body: some View {
        NavigationStack {
            Button("Show settings") {
                isPresentingSettings = true
            }
            .navigationTitle("Home")
            .sheet(isPresented: $isPresentingSettings) {
                SettingsView()
                    .interactiveDismissDisabled(true)
            }
        }
    }
}
import SwiftUI

struct SettingsView: View {
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Text("Settings")
                .navigationTitle("Settings")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    Button("Cancel") {
                        dismiss()
                    }
                }
        }
    }
}

Upvotes: 0

hstdt
hstdt

Reputation: 6261

iOS 14: workaround -> fullScreenCover

fullScreenCover(isPresented:onDismiss:content:)

https://developer.apple.com/documentation/swiftui/view/fullscreencover(ispresented:ondismiss:content:)

iOS 15: interactiveDismissDisabled

.interactiveDismissDisabled(false)

https://developer.apple.com/documentation/swiftui/path/interactivedismissdisabled(_:)

Upvotes: 17

swift code
swift code

Reputation: 115

We have created a SwiftUI style extension, at https://gist.github.com/mobilinked/9b6086b3760bcf1e5432932dad0813c0

/// Example:
struct ContentView: View {
    @State private var presenting = false
    
    var body: some View {
        VStack {
            Button {
                presenting = true
            } label: {
                Text("Present")
            }
        }
        .sheet(isPresented: $presenting) {
            ModalContent()
                .allowAutoDismiss { false }
        }
    }
}

Upvotes: 5

Junyi Wang
Junyi Wang

Reputation: 154

If you are using swiftUI, you may find this useful

https://github.com/egeniq/BetterSheet

It has the feature you want.

---Edited---

Revisit the problem after months. If you don't want extra library, https://stackoverflow.com/a/61239704/10800901 would serve you well. Very elegant solution. Work like a charm.

Upvotes: 3

Related Questions