Search code examples
swiftswiftuiios13tabview

How to show a badge number on a tabItem of a TabView in SwiftUI?


I'm working on a side project with SwiftUI, and I have a scenario where I need to show a badge number on one of the tabItems of my TabView.

I have everything set with my models, and binding and so on. But I have been looking for 2 days now to find a modifier to show the badge, but unfortunately all my researches had faced a dead end.

I had went through Apple SwiftUI API Documentation for TabView and searched here on stack overflow and also of course tons of google search results' links.

I'm observing an environment object which hold a list of items and I know how to bind the badge with my items count, so when I have any item update (added, deleted) the badge will be updated. But I'm unable to find a way to show the badge number itself on the tabItem.

Any help is very appreciated!


Solution

  • There are no modifiers for setting badge number on tab item and If you try to add custom view for that, it won't be visible; This is from TabView documentation:

    Tab views only support tab items of type Text, Image, or an image followed by text. Passing any other type of view results in a visible but empty tab item.

    So, I tried a workaround and it works. Using ZStack with GeometryReader and some calculations to place the custom badge view in the right place.

    struct ContentView: View {
      @State private var badgeNumber: Int = 3
      private var badgePosition: CGFloat = 3
      private var tabsCount: CGFloat = 3
    
      var body: some View {
        GeometryReader { geometry in
          ZStack(alignment: .bottomLeading) {
            // TabView
            TabView {
              Text("First View")
                .tabItem {
                  Image(systemName: "1.circle")
                  Text("First")
              }.tag(0)
    
              Text("Second View")
                .tabItem {
                  Image(systemName: "2.circle")
                  Text("Second")
              }.tag(1)
    
              Text("Third View")
                .tabItem {
                  Image(systemName: "3.circle")
                  Text("Third")
              }.tag(2)
            }
    
            // Badge View
            ZStack {
              Circle()
                .foregroundColor(.red)
    
              Text("\(self.badgeNumber)")
                .foregroundColor(.white)
                .font(Font.system(size: 12))
            }
            .frame(width: 20, height: 20)
            .offset(x: ( ( 2 * self.badgePosition) - 1 ) * ( geometry.size.width / ( 2 * self.tabsCount ) ), y: -30)
            .opacity(self.badgeNumber == 0 ? 0 : 1)
          }
        }
      }
    }
    

    The sample project available on github: https://github.com/aelzohry/TabBarSwiftUI