递增标签栏徽章W / UIAlertAction迅速?

@IBAction func addToCart(sender: AnyObject) { let itemObjectTitle = itemObject.valueForKey("itemDescription") as! String let alertController = UIAlertController(title: "Add \(itemObjectTitle) to cart?", message: "", preferredStyle: .Alert) let yesAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { (action) in var tabArray = self.tabBarController?.tabBar.items as NSArray! var tabItem = tabArray.objectAtIndex(1) as! UITabBarItem let badgeValue = "1" if let x = badgeValue.toInt() { tabItem.badgeValue = "\(x)" } } 

我不知道为什么我不能只做+ =“(x)”

错误:二元运算符'+ ='不能应用于'String'types的操作数 和“string”

每次用户select“是”时,我都希望它增加1。 现在显然它只是停留在1。

您可以尝试访问badgeValue并将其转换为Integer,如下所示:

Swift 2

 if let badgeValue = tabBarController?.tabBar.items?[1].badgeValue, nextValue = Int(badgeValue)?.successor() { tabBarController?.tabBar.items?[1].badgeValue = String(nextValue) } else { tabBarController?.tabBar.items?[1].badgeValue = "1" } 

Swift 3或更高版本

  if let badgeValue = tabBarController?.tabBar.items?[1].badgeValue, let value = Int(badgeValue) { tabBarController?.tabBar.items?[1].badgeValue = String(value + 1) } else { tabBarController?.tabBar.items?[1].badgeValue = "1" } 

要删除徽章,只需将badge分配给badgeValue重写viewDidAppear方法:

 override func viewDidAppear(animated: Bool) { tabBarController?.tabBar.items?[1].badgeValue = nil } 

适用于Swift 2:

  let tabController = UIApplication.sharedApplication().windows.first?.rootViewController as? UITabBarController let tabArray = tabController!.tabBar.items as NSArray! let alertTabItem = tabArray.objectAtIndex(2) as! UITabBarItem if let badgeValue = (alertTabItem.badgeValue) { let intValue = Int(badgeValue) alertTabItem.badgeValue = (intValue! + 1).description print(intValue) } else { alertTabItem.badgeValue = "1" }