iosswiftswiftuimobile

TabBar delay showing when using toolbar(.hidden, for: .tabBar)


I use toolbar(.hidden, for: .tabBar) modifier to hide the tab bar in the NotificationSettingScreen. When I navigate back, SwiftUI takes a moment to re-render the tab bar, causing the delay of showing the tab bar. how to make it show instantly?

struct NotificationMenuButton: View {
    var body: some View {
        Menu {
            NavigationLink(
                destination: NotificationSettingScreen()
                    .toolbar(.hidden, for: .tabBar)
            ) {
                Text("Notification Settings")
            }
        } label: {
            Label("Options", systemImage: "ellipsis.circle")
        }
    }
}
struct NotificationScreen: View {
    @EnvironmentObject private var notificationVM: NotificationViewModel

    var body: some View {
        NavigationStack {
            NotificationMenuButton()
        }
    }
}

import SwiftUI

struct MainScreen: View {
    @State private var selectedTabIdx = 1

    var body: some View {
        TabView(selection: $selectedTabIdx) {
            NotificationScreen()
                .tabItem {
                    Label(
                        "Notifications",
                        systemImage: hasUnreadNotifications
                            ? "bell.badge.fill"
                            : "bell"
                    )
                }
                .tag(1)

        }
    }
}


Solution

  • This problem can be solved by using a state variable to control the visibility of the tab-bar.

    struct NotificationMenuButton: View {
        @State private var toolbarVisibility = Visibility.visible
    
        var body: some View {
            Menu {
                NavigationLink("Notification Settings") {
                    NotificationSettingScreen()
                        .onAppear { toolbarVisibility = .hidden }
                }
                .onAppear { toolbarVisibility = .visible }
            } label: {
                Label("Options", systemImage: "ellipsis.circle")
            }
            // Pre iOS 18: .toolbar(toolbarVisibility, for: .tabBar)
            .toolbarVisibility(toolbarVisibility, for: .tabBar)
        }
    }
    

    Animation