简体   繁体   中英

Setting badge on a tabbar item of chosen type (without knowing its index)

I have a tabBar in my app. I want to display a badge with a number of unread messages when notification comes. So far my code is below. The problem is that the messages tab isn't always the first item in the list (the order varies for different app settings, but it's always there). How do I set the badge on it if I don't know which index it has?

    if let item = self.tabBar.items?.first {
    var count = messages.count
        if item.badgeValue != nil {
            count += Int(item.badgeValue!) ?? 0
        }
        item.badgeValue = "\(count)"
    }

You are getting first item in first line - so it's working as expected. You need to organize your UITabBar this way, that you can always identify on which index messages are presented.

One idea would be to keep a reference to it when you configure your UITabBar - this way that you can always find under which index messages are shown. Best way would be to keep corresponding array of views you keep behind your UITabBar , and then find the one you need.

If you are using UITabBarController you will get it for free - all UIViewController are accessible directly via property named viewControllers .

If you have custom ViewController and just UITabBar - you just need to build similar logic that will allow you to keep track on which index certain view controller is shown.

Assuming your tabbar is managed by a UITabBarController , you can determine the index by checking the type of the view controllers in your tab bar controller.

class MessagesViewController: UIViewController {
    // ... your messages vc
}

if let index = tabbarController.viewControllers?.firstIndex(where: { $0 is MessagesViewController }) {
    tabbarController.tabBar.items?[index].badgeValue = "..."
}

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