Dismissing underlying sheet when an alert is shown #81
-
I have a button on a sheet, when pressed opens up an alert. Is it possible to dismiss the underlying sheet when the alert is displayed? Otherwise I get this weird behaviour, when pressing cancel, the alert disappears then the sheet. The same issue is when opening a Here's some sample code about the issue: import SwiftUI
import SwiftUINavigation
struct SampleSheet: View {
@StateObject var sampleSheetViewModel: SampleSheetViewModel = SampleSheetViewModel()
var body: some View {
VStack {
Button {
sampleSheetViewModel.openSheet()
} label: {
Text("Main screen")
}
.sheet(
unwrapping: self.$sampleSheetViewModel.destination,
case: /SampleSheetViewModel.Destination.someSheet
) { _ in
SheetContent()
}
}
}
}
struct SheetContent: View {
@StateObject var sheetContentViewModel: SheetContentViewModel = SheetContentViewModel()
@Environment(\.dismiss) var dismiss
var body: some View {
Button {
sheetContentViewModel.destination = .alert(
AlertState(
title: {
TextState("Some random alert")
},
actions: {
ButtonState(
action: .send(.okay),
label: {
TextState("OK")
})
})
)
} label: {
Text("Hello")
}
.alert(
unwrapping: self.$sheetContentViewModel.destination,
case: /SheetContentViewModel.Destination.alert
) { action in
switch action {
case .okay:
dismiss()
case nil:
break
}
}
}
}
class SheetContentViewModel: ObservableObject {
@Published var destination: Destination?
enum Destination {
case alert(AlertState<AlertAction>)
}
enum AlertAction {
case okay
}
}
class SampleSheetViewModel: ObservableObject {
@Published var destination: Destination?
enum Destination {
case someSheet
}
func openSheet() {
self.destination = .someSheet
}
} Sample video: Screen.Recording.2023-02-05.at.16.43.48.mov |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Hey @Muhammed9991! |
Beta Was this translation helpful? Give feedback.
Hey @Muhammed9991!
I don't find the effect particularly weird, but in any case, you can't dismiss the sheet while the alert is presented if the alert is itself anchored to the sheet's content. In other words, the alert needs the sheet content to exist. BTW, you're not cancelling when "OK" is pressed here, you're effectively calling
dismiss
for the sheet presentation, so the sheet being dismissed makes sense. Alerts (or confirmation dialogs) always dismiss themselves when you interact with any button.If this is indeed the behavior that you're looking for, you can maybe add the alert besides the sheet instead of inside, as in this case, the alert will be able to exist independently of the …