How to set the tab bar badge with swift?

Faris picture Faris · Mar 30, 2017 · Viewed 31.2k times · Source

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 !

Answer

Lepidopteron picture Lepidopteron · Mar 30, 2017

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