来自array.count的UITabBar徽章

时间:2018-04-27 22:11:48

标签: ios swift uitabbar badge

如何在swift中添加到array.count的UITabBar Badge个计数?

我有UserDefaults数组,我想在Badge中显示可变数组计数的数量,请帮忙

1 个答案:

答案 0 :(得分:1)

这是您需要设置徽章值的视图控制器的类。

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)")
         }
    }
}

这是一个视图控制器类,您需要点击一个按钮来更新YourViewController的徽章值。

class AnotherViewController: UIViewController {

   @IBAction func buttonPressed() {
       YourViewController?.shared.updateBadgeValue()
   }
}