Update badge of non selected tabBarItem in Swift

坚强是说给别人听的谎言 提交于 2019-12-09 04:44:30

问题


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 notification, no matter in what view or tab am I. I need to use the auto-layout so I can't use any programmatically solution inside the app delegate. I started the project from a single view template.

I tried to go to the desired tab, change the badge value and come back but of course it didn't work. The tabBarController seems to have only references to the current tab bar item.

    var current = self.tabBarController?.selectedIndex
    self.tabBarController?.selectedIndex = 3
    self.navigationController?.tabBarItem.badgeValue = "34"
    self.tabBarController?.selectedIndex = current!

回答1:


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"
}



回答2:


Shorter:

let tabItem = self.tabBarController?.tabBar.items![3]
let tabItem.badgeValue = "34"



回答3:


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")


来源:https://stackoverflow.com/questions/27161672/update-badge-of-non-selected-tabbaritem-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!