Changing between tab bar and sidebar in swiftUI

Hi, is there a way to switch between side bar and tab bar depending on the size class of the app? I would like to have a tab bar on a compact layout and a sidebar on a regular layout.
Answered by espen in 620997022
Yes, use horizontalSizeClass. Here is an example:

Code Block Swift
struct ContentView: View {
    
    #if os(iOS)
    @Environment(\.horizontalSizeClass) private var horizontalSizeClass
    #endif
    
    @ViewBuilder var body: some View {
        
        #if os(iOS)
        if horizontalSizeClass == .compact {
            AppTabNavigation()
        } else {
            AppSidebarNavigation()
        }
        #elseif os(watchOS)
        AppTabNavigation()
        #elseif os(tvOS)
        AppTabNavigation()
        #else
        AppSidebarNavigation()
            .frame(minWidth: 900, maxWidth: .infinity, minHeight: 500, maxHeight: .infinity)
        #endif
    }
}


Accepted Answer
Yes, use horizontalSizeClass. Here is an example:

Code Block Swift
struct ContentView: View {
    
    #if os(iOS)
    @Environment(\.horizontalSizeClass) private var horizontalSizeClass
    #endif
    
    @ViewBuilder var body: some View {
        
        #if os(iOS)
        if horizontalSizeClass == .compact {
            AppTabNavigation()
        } else {
            AppSidebarNavigation()
        }
        #elseif os(watchOS)
        AppTabNavigation()
        #elseif os(tvOS)
        AppTabNavigation()
        #else
        AppSidebarNavigation()
            .frame(minWidth: 900, maxWidth: .infinity, minHeight: 500, maxHeight: .infinity)
        #endif
    }
}


According to the session video, you set UISplitViewController.setViewController(myTabBarVC, for: .compact) and it will automatically switch for you.
Changing between tab bar and sidebar in swiftUI
 
 
Q