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

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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Mike
  • 85
  • 1
  • 9

2 Answers2

11

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
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

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"
            }
Mostafa
  • 1,522
  • 2
  • 18
  • 34