简体   繁体   English

如何从所有视图控制器更新徽章计数?

[英]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. 在我的应用中,徽章计数可以随时更改,因为它是实时聊天应用,用户可以通过Android,Web和iOS应用进行聊天。

Right now I'm fetching badge counts in each and every view controller in my app in viewWillAppear . 现在,我正在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 TX

You can create subclass of UITabBarController (then you have to set class of your TabBarController to this subclass). 您可以创建UITabBarController子类(然后您必须将TabBarController的类设置为该子类)。 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 现在,在create方法和此方法内部,声明当当前selectedItem这个tabBaritems数组中的这个 UITabBarItem时应该怎么tabBar

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 现在,当TabBarController确实加载并且用户选择新的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 . 当你有tabBarController的共享实例的访问,你可以轻松地增加任何的UIViewController它的TabBar项目的徽章价值。 You can do this by following: 您可以按照以下步骤进行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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