Update badge of non selected tabBarItem in Swift

后端 未结 3 700
忘掉有多难
忘掉有多难 2021-02-05 19:50

I have a navigation controller with 4 tab bar items. Each one has a navigation controller inside. I want to be able to change the 4th tab bar badge number when I get push notifi

相关标签:
3条回答
  • 2021-02-05 20:30

    Shorter:

    let tabItem = self.tabBarController?.tabBar.items![3]
    let tabItem.badgeValue = "34"
    
    0 讨论(0)
  • 2021-02-05 20:33

    No need to select that index to update badge value. Take an array of tab bar items. The select item at the index which you want to update and then set it badge value. See below I have done for 4th tab bar item.

    Swift 5.0

    if let items = self.tabBarController?.tabBar.items as NSArray? {
        let tabItem = items.object(at: 3) as! UITabBarItem
        tabItem.badgeValue = "34"
    }
    
    0 讨论(0)
  • 2021-02-05 20:43
    extension UITabBarController {
        func increaseBadge(indexOfTab: Int, num: String) {
            let tabItem = tabBar.items![indexOfTab]
            tabItem.badgeValue = num
        } 
    }
    

    and you can call it like this:

    self.tabBarController?.increaseBadge(indexOfTab: 3, num: "34")
    
    0 讨论(0)
提交回复
热议问题