Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Customize Tab View Appearance in SwiftUI
Written by Team Kodeco

In SwiftUI, the TabView is a common user interface component, and its appearance can be customized in various ways. An especially useful customization involves controlling the visibility and color of the toolbar background using the toolbarBackground modifier.

This modifier allows you to change the background color and visibility of a toolbar in a TabView. You can set the visibility to .visible to keep the toolbar always visible, or to .hidden to hide it.

Let’s look at an example with a TabView that has three tabs, each with different toolbar backgrounds:

struct ContentView: View {
  var body: some View {
    TabView {
      Text("First Tab")
        .tabItem {
          Image(systemName: "1.square.fill")
          Text("First")
        }
        .tag(1)
        .toolbarBackground(.hidden, for: .tabBar)

      Text("Second Tab")
        .tabItem {
          Image(systemName: "2.square.fill")
          Text("Second")
        }
        .tag(2)
        .toolbarBackground(.visible, for: .tabBar)
        .toolbarBackground(Color.orange.opacity(0.8), for: .tabBar)

      Text("Third Tab")
        .tabItem {
          Image(systemName: "3.square.fill")
          Text("Third")
        }
        .tag(3)
    }
  }
}

Tap the second tab and your preview should look like this:

TabView with a custom background in SwiftUI.
TabView with a custom background in SwiftUI.

In the above code snippet:

  • A TabView is created with three tabs. Each tab contains text and is decorated with an image and a label using the .tabItem modifier.
  • For the first tab, you’ve used .toolbarBackground(.hidden, for: .tabBar). This hides the tab bar’s background.
  • For the second tab, you’ve applied two toolbarBackground modifiers. The first one, .toolbarBackground(.visible, for: .tabBar), ensures the tab bar remains visible. The second one, .toolbarBackground(Color.orange.opacity(0.8), for: .tabBar), changes the background color to a translucent orange.
  • The third tab doesn’t have any toolbarBackground modifier, so it uses the default SwiftUI behavior.

This level of customization provides you with more control over the appearance of your SwiftUI tabs, allowing you to create a more engaging and user-friendly interface that aligns with your app’s design.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.