Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add Custom Icons to Tab View Items in SwiftUI
Written by Team Kodeco

Tab views are a great way to organize your app’s user interface, and adding custom icons to the tab view items can make it even more visually appealing and user-friendly.

To add custom icons to the tab view items, you’ll first need to create the image assets that you want to use as the icon. Note that SwiftUI’s resizable and frame modifiers are not available on tab items, so images need to be scaled down ahead of time. Once you have your images prepared, drag the image files into the asset catalog in your Xcode project.

Next, create a tab view and set the image property of each tab view item to the image asset that you created. Here’s an example:

struct ContentView: View {
  var body: some View {
    TabView {
      Text("Here comes the sun 🎶 !")
        .tabItem {
          Image("HappySun")
          Text("Sun")
        }
      Text("I see a good moon rising 🎶 !")
        .tabItem {
          Image("HappyMoon")
          Text("Moon")
        }
    }
  }
}

Your preview should look like this:

You can use your own images on tabs.
You can use your own images on tabs.

Note: If you want to try out this example, you can download an archive of the tab images here.

In the above code, you create a tab view with two tab view items, and set the image property of each tab view item to the name of the custom image you’ve added to your asset catalog.

And that’s it! Now you know how to add icons to the tab view items in SwiftUI. With just a few lines of code, you can improve the user experience of your app and make it more visually appealing.

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.