'SwiftUI view popping back after button click
This is a question that I already have the answer to, but I just thought I'd share it here in case someone gets absolutely mad too over something similar.
I realised that my detail view was popping back whenever user interacted with it, by tapping somewhere and I couldn't figure it out why.
The detail view had 2 alerts, one single action and one double action. Since in SwiftUI you can't have 2 sequential alerts applied to the same view I usually add a Spacer() in between in order to make both of them appear.
Pls check answer with fix.
Solution 1:[1]
This is the code with the 2 alerts I had in that view
.alert(isPresented: $alertCoordinator.isShowingDoubleAction) {
Alert(
title: Text(alertCoordinator.title),
message: Text(alertCoordinator.message),
primaryButton: .cancel(),
secondaryButton: .destructive(
alertCoordinator.secondaryTitle,
action: { alertCoordinator.secondaryAction?() }
)
)
}
Spacer()
.alert(isPresented: $alertCoordinator.isShowingSingleAction) {
Alert(
title: Text(alertCoordinator.title),
message: Text(alertCoordinator.message),
dismissButton: .default(
alertCoordinator.primaryTitle,
action: { alertCoordinator.primaryAction?() }
)
)
}
For some weird reason adding the spacer in there was causing the view to pop back and as soon as I replaced it with an EmptyView() it all worked well and the issue went away.
If you know why this happens I'd love to know! Hope this helps someone facing this issue ?
Solution 2:[2]
In the case that this is deep in a NavigationView, could you try adding this line to your NavigationView:
.navigationViewStyle(.stack)
Otherwise these links might be able to help you:
SwiftUI sheet automatically dismisses itself
SwiftUI NavigationView pops back when updating ObservableObject
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcela Ceneviva Auslenter |
| Solution 2 | Kim |
