iosswiftuiswiftui-tabviewswiftui-navigationstack

SwiftUI TabView hidden tabbar navigation stack animation order issue


I am having the following view:


import SwiftUI

struct HiddenTabs: View {
    var body: some View {
        TabView {
            NavigationStack {
                NavigationLink("Tap Me") {
                    Text("Detail View")
                        .toolbar(.hidden, for: .tabBar)
                }
                .padding()
                .background(.secondary)
                .navigationTitle("Primary View")
            }
            .tabItem {
                Label("Home", systemImage: "house")
            }
        }.background(.purple)
    }
}

#Preview {
    HiddenTabs()
}

It works fine, but the tabs appearance after the back button press on navigation view is too late and causes the whole content of the tab to jump up.

Is it possible to make tabs appearance don't cause content jump? Ideally, I don't want any animation besides NavigationStack "< Back".

example


Solution

  • The post How do I animate hiding and showing tab bar in SwiftUI? explores ways of animating the change in tabbar visibility.

    You said in a comment, that you don't need animation. In which case, it may be sufficient to use a state variable to determine the visibility.

    I found it works best to update the state variable in separate .onAppear callbacks for the NavigationLink and its destination. If instead you try to reset it in .onDisappear for the destination, there is still a jump.

    @State private var toolbarVisibility = Visibility.visible
    
    NavigationStack {
        NavigationLink("Tap Me") {
            Text("Detail View")
                .onAppear { toolbarVisibility = .hidden }
        }
        .padding()
        .background(.secondary)
        .navigationTitle("Primary View")
        .onAppear { toolbarVisibility = .visible }
    }
    .toolbar(toolbarVisibility, for: .tabBar)
    .tabItem {
        Label("Home", systemImage: "house")
    }
    

    Animation