60

How to set the tab bar badge with swift ? for example when I get new message showing number 1 on the message icon ! Do I have to use the UITabBarItem.swift and write the code in it ! I'm not really sure how I can do it

Thank you !

Lepidopteron
  • 6,056
  • 5
  • 41
  • 53
Faris
  • 1,206
  • 1
  • 12
  • 18

7 Answers7

148

If you got the reference to the tabBarController (e.g. from the UIViewController) you can do the following:

if let tabItems = tabBarController?.tabBar.items {
    // In this case we want to modify the badge number of the third tab:
    let tabItem = tabItems[2]
    tabItem.badgeValue = "1"
}

From a UITabBarController it would be tabBar.items instead of tabBarController?.tabBar.items

and to delete the badge:

tabItem.badgeValue = nil
vrwim
  • 13,020
  • 13
  • 63
  • 118
Lepidopteron
  • 6,056
  • 5
  • 41
  • 53
  • I meant to use this inside aViewcontroller that has a TableView in it. and make the badge show how many cells are inside the tableView – Joe Sene Apr 04 '17 at 12:48
  • instead of "1" use the following: tabItem.badgeValue = self.tableView.dataSource.numberOfRowsInSection(self.tableView) – Lepidopteron Apr 04 '17 at 12:56
  • It worked, altho I can make it show as soon as the app launches, it only shows the badge when I click on the item. – Joe Sene Apr 04 '17 at 13:04
  • Well, either the tableview's data is only loaded, when the viewWillAppear/viewDidAppear is called OR the setting of the tabBar's item is happening in one of those methods. You would have to move your code to "viewDidLoad". For huge datacalls, I would still recommend to not pack everything in the viewDidLoad, as the TabBarController has to load all tabs. If all tabs perform processing intense operations, your app would launch a bit slowly :) – Lepidopteron Apr 04 '17 at 13:06
19

The following line may help you to show badge in UITabBerItem

tabBarController?.tabBar.items?[your_desired_tabBer_item_number].badgeValue = value
Rupom
  • 429
  • 5
  • 10
  • 3
    Please add an explanation with your code. Code only answers are considered low quality and are often downvoted and may even be deleted. Please see [answer] – Bugs Jun 15 '17 at 09:10
  • 2
    1) tabBarController? - unwrapped because we don't actually kwon if it exist from our UIVewController 2) .tabBar.items? - asking an array of items in tabBar that is in UITabBarController, also unwrapped because we don't know does this array initialized with at least one UITabBarItem 3) .[UITabBarItem index in array] 4) .badgeValue - string value of badge for UITabBarItem that you want to see. – Mykyta Savchuk Feb 01 '18 at 08:53
9

One can also set an empty string for the badge value to get a red circle if desired:

tabBarController?.tabBar.items?.last?.badgeValue = ""

enter image description here

Debaprio B
  • 503
  • 7
  • 9
8

Set badgeValue in ViewDidAppear. Otherwise it may not appear from app loading.

import UIKit

class TabBarController: UITabBarController {

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

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

}

No safe checks since you are in general sure that you have TabBar with n tabs.

Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70
6

I took the @Victor code and put it in an extension to make the code smaller in the view.

import UIKit

extension UITabBar {
    func addBadge(index:Int) {
        if let tabItems = self.items {
            let tabItem = tabItems[index]
            tabItem.badgeValue = "●"
            tabItem.badgeColor = .clear
            tabItem.setBadgeTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)
        }
    }
    func removeBadge(index:Int) {
        if let tabItems = self.items {
            let tabItem = tabItems[index]
            tabItem.badgeValue = nil
        }
    }
    
 }


Application: 

 tabBarController?.tabBar.addBadge(index: 1)

 tabBarController?.tabBar.removeBadge(index: 1)



1

Thanks to @Lepidopteron, instant solution for me. In addition, you can do it with the index of selected tab index:

let tabItems = self.tabBarController?.tabBar.items as NSArray!
    var selectedIndex = tabBarController!.selectedIndex //here 
    let tabItem = tabItems![selectedIndex] as! UITabBarItem
    tabItem.badgeValue = "2"

Got the reference from this post

Andres Paladines
  • 1,142
  • 14
  • 19
0
func showHideInnerBagde(value:String,indexValue:Int) {
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let sceneDelegate = windowScene.delegate as? SceneDelegate,
           let navController = sceneDelegate.window?.rootViewController as? UINavigationController,
           let visibleController = navController.visibleViewController,
           let tabbarController = visibleController as? UITabBarController,
           tabbarController.tabBar.items?.indices.contains(2) ?? false {
            
            let tabIndex = indexValue
            tabbarController.tabBar.items?[tabIndex].badgeValue = value
            tabbarController.tabBar.items?[tabIndex].badgeColor = UIColor.clear
            
            let attributes: [NSAttributedString.Key: Any] = [
                NSAttributedString.Key.foregroundColor: UIColor.red,
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12) // Set your desired font
            ]
            tabbarController.tabBar.items?[tabIndex].setBadgeTextAttributes(attributes, for: .normal)
        } else {
            // Handle the case when the conditions are not met or the tab at index 2 does not exist.
            print("Unable to set badge value and text attributes.")
        }
    }
Davender Verma
  • 503
  • 2
  • 12