Increment tab bar badge w/ UIAlertAction swift?

2019-01-12 01:19发布

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

I don't know why I can't just do += "(x)"

Error: binary operator '+=' cannot be applied to operands of type 'String?' and 'String'

I want it to increment by 1 each time the user selects "Yes". Right now obviously it just stays at 1.

2条回答
放荡不羁爱自由
2楼-- · 2019-01-12 01:52

Works with 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"
            }
查看更多
爷、活的狠高调
3楼-- · 2019-01-12 02:04

You can try to access the badgeValue and convert it to Integer as follow:

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 or later

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

To delete the badge just assign nil to the badgeValue overriding viewDidAppear method:

override func viewDidAppear(animated: Bool) {
    tabBarController?.tabBar.items?[1].badgeValue = nil
}
查看更多
登录 后发表回答