SwiftUI Alert is being presented in the wrong view

49 Views Asked by At

My SwiftUI app incorporates a tab view with 4 tabs and upon entering each tabView , the tab Selection is updated. On my second tab view I trigger alerts and also a text pop over. When these are triggered they show up on the first tab View , and not on the second tab view of which they are being triggered from. Consequently, when my alert pops up (or when the text pop over pops up) , my View instantly jumps to the first tab view. It is supposed to be showing the alerts and the text pop over only on the second tab view.

I don't understand why the alert is triggering the UI to jump back to the first tab view.

I notice that when I enter a child view from the second tab view and then navigate back to the second tab , I see the correct expected behaviour of the alerts showing on the second tab view page. It looks as though when I enter a child view, the second tab view gets pushed to a navigation stack whereas, this doesn't happen when using the TabView and that's why the alerts are shown on the first tab view rather than the second.

How can I fix this issue?

My tabView looks like this:

    @State var tabSelection: Int

    
    var body: some View {

        TabView(selection:$tabSelection){
            Home(tabSelection: $tabSelection)
                .tabItem(){
                    Image(systemName: "house")
                }
                .tag(1)
            Products(tabSelection: $tabSelection)
                .tabItem(){
                    Image(systemName: "birthday.cake")
                }
                .tag(2)
            Orders(tabSelection: $tabSelection)
                .tabItem(){
                    Image(systemName: "list.bullet")
                }
                .tag(3)
            Account(tabSelection: $tabSelection)
                .tabItem(){
                    Image(systemName: "person")
                }
                .tag(4)

}

Each Tab page updates the tab selection as a @Binding variable in this way (For example):

    .onAppear(){
        tabSelection = 2
    }

On the second tab view my alert is being called from the parent VStack.

@State private var test = false

var body: some View {
    

        VStack{

              ...
        }
        .onAppear(){
            tabSelection = 2
            test = true

        }
        .alert("Test", isPresented: $test) {Button("OK", role: .cancel) { } }

I have also tried wrapping the second tab view VStack within a NavigationStack and it didn't work.

0

There are 0 best solutions below