Tab icon with 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 increase by 1 every time the user selects "Yes". Right now, obviously, he remains at level 1.

+3


source to share


2 answers


You can try to access the badgeValue badge and convert it to Integer like this:

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 remove a badge, simply assign nil to the badgeValue badge, overriding the viewDidAppear method:

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

      

+10


source


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

      

+1


source







All Articles