Search code examples
iosswiftswift2swift3uitabbaritem

Increment tab bar badge w/ UIAlertAction swift?


@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.


Solution

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