简体   繁体   中英

How to update badge count from all view controllers?

I've bunch of badges displaying in tab bar. In my app the badge counts can change anytime as it's a realtime chat app and users can chat from Android, web and iOS app.

Right now I'm fetching badge counts in each and every view controller in my app in viewWillAppear . It works but I'm not sure if it's the best way to do it?

Is there any better way to handle this? Any pointer will be appreciated. Tx

You can create subclass of UITabBarController (then you have to set class of your TabBarController to this subclass). Now inside create method and inside this method declare what should happen when current selectedItem is this or this UITabBarItem from tabBar 's items array

func changeBadge() {
    guard let item = tabBar.selectedItem else { return }
    guard let items = tabBar.items else { return }
    switch item {
    case items[0]:
        ... // get value
        item.badgeValue = "\(value)"
    case items[1]
        ... // get value
        item.badgeValue = "\(value)"
    ...
    default:
    }
}

Now just call this method when TabBarController did load and when user select new UITabBarItem

override func viewDidLoad() {
    changeBadge()
}

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    changeBadge()
}

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        changeBadge()
    }

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        changeBadge()
    }

    func changeBadge() {
        guard let item = tabBar.selectedItem else { return }
        guard let items = tabBar.items else { return }
        switch item {
        case items[0]:
            ... // get value
            item.badgeValue = "\(value)"
        case items[1]
            ... // get value
            item.badgeValue = "\(value)"
        ...
        default:
        }
    }

}

As you have access of shared instance of tabBarController , you can easily increase badge value of its tabBar item in any UIViewController . You can do this by following:

if let tabBarItems = tabBarController?.tabBar.items {
     let tabItem = tabBarItems[0]
     tabItem.badgeValue = "1"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM