3
@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)"

错误:二元运算符“+=”不能应用于“字符串?”类型的操作数 和“字符串”

每次用户选择“是”时,我希望它增加 1。现在显然它只是保持在1。

4

2 回答 2

11

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

斯威夫特 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"
}

斯威夫特 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"
    }

要删除徽章,只需将 nil 分配给 badgeValue 覆盖 viewDidAppear 方法:

override func viewDidAppear(animated: Bool) {
    tabBarController?.tabBar.items?[1].badgeValue = nil
}
于 2015-04-24T02:59:18.903 回答
1

适用于 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"
            }
于 2016-03-04T18:24:14.497 回答