Search code examples
xcodeswiftuitabviewtabitem

Add a badge value in SwiftUI in a simple way for a TabView tabItem


Is it possible to add a badge value in SwiftUI in a simple way for a TabView tabItem?

Like this (normal Swift here) :

import UIKit

class TabBarController: UITabBarController {

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.tabBar.items![2].badgeValue = "7"
}

}

Thanks


Solution

  • There is no property of badge count on TabViewItem in SwiftUI so you have to manually add a ZStack on top of TabViewItem and do some calculation.

    struct ContentView: View {
      @State private var badgeNumber: Int = 10
      private var badgePosition: CGFloat = 1
      private var tabsCount: CGFloat = 1
    
      var body: some View {
        GeometryReader { geometry in
          ZStack(alignment: .bottomLeading) {
            // TabView
            TabView {
              Text("First View")
                .tabItem {
                  Image(systemName: "tray.fill")
                  Text("First")
              }
            }
    
            // 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)
          }
        }
      }
    }