How to set the tab bar badge with swift?
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
The following line may help you to show badge in UITabBerItem
tabBarController?.tabBar.items?[your_desired_tabBer_item_number].badgeValue = value
Set badgeValue
in ViewDidAppear
. Otherwise it may not appear from app loading.
import UIKitclass 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.