来自 array.count 的 UITabBar 徽章

UITabBar Badge from array.count

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

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

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

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

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

class AnotherViewController: UIViewController {

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