Search code examples
iosswiftuitabbarbadge

UITabBar Badge from array.count


how in swift can I add to UITabBar Badge counts from array.count?

I have UserDefaults array, and I want to display number of changeable array counts in Badge, please help


Solution

  • This is the class of your view controller where you need to set badge value.

    class YourViewController: UIViewController {
    
        static weak var shared: YourViewController?
    
    
        override function viewDidLoad() {
            super.viewDidLoad()
    
            YourViewController.shared = self
        }
    
    
    
    
       public func updateBadgeValue() {
    
          guard let array = UserDefaults.standard.value(forKey: "yourKeyOfStoredArray") as? [Any]  else { //raplace yourKeyOfStoredArray to the key you use to store the array
    
             print("Don't have a stored array for key yourKeyOfStoredArray")
             return
          }
    
          guard let items = self.tabBarController?.tabBar.items else { // Only if you use tab bar controller, if no delete this scope and uncomment next
    
             print("Don't have tab bar controller")
             return
           }
    
    
           /*
            guard let items = self.tabBar.items  else { // replace tabBar by reffence to your tab bar @IBOutlet
    
                print("Don't have tab bar")
                return
             }*/
    
    
    
             let index = 0 //<-The index of the tabbar item which you need to set badge value
    
             if items.count > index {
                 items[index].badgeValue = String(array.count)
             } else {
                    print("Don't have item at index \(index)")
             }
        }
    }
    

    This is the class of view controller where you need to tap a button to update badge value of YourViewController.

    class AnotherViewController: UIViewController {
    
       @IBAction func buttonPressed() {
           YourViewController?.shared.updateBadgeValue()
       }
    }