Home > Back-end >  SwiftUI view popping back after button click
SwiftUI view popping back after button click

Time:04-09

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.

CodePudding user response:

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

  • Related