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

How to update badge count from all view controllers?

我在标签栏中显示了一堆徽章。在我的应用程序中,徽章计数可以随时更改,因为它是一个实时聊天应用程序,用户可以从 Android、网络和 iOS 应用程序聊天。

现在,我正在 viewWillAppear 中的应用程序的每个视图控制器中获取徽章计数。它有效,但我不确定这是否是最好的方法?

有没有更好的方法来处理这个问题?任何指针将不胜感激。发送

您可以创建 UITabBarController 的子class(然后您必须将 TabBarController 的 class 设置为该子class)。现在在 create 方法和这个方法中声明当当前 selectedItemthisthis UITabBarItem 来自 tabBaritems数组

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

现在只需在 TabBarController 加载和用户 select 新 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:
        }
    }

}

由于您可以访问 tabBarController 的共享实例,因此您可以轻松地在任何 UIViewController 中增加其 tabBar 项目的徽章值。您可以通过以下方式执行此操作:

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