How to set the tab bar badge with swift?

Solution 1:

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

Solution 2:

The following line may help you to show badge in UITabBerItem

tabBarController?.tabBar.items?[your_desired_tabBer_item_number].badgeValue = value

Solution 3:

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.

Solution 4:

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