Increment tab bar badge w/ UIAlertAction swift?

前端 未结 2 844
故里飘歌
故里飘歌 2020-12-03 19:56
@IBAction func addToCart(sender: AnyObject) {
    let itemObjectTitle = itemObject.valueForKey(\"itemDescription\") as! String
    let alertController = UIAlertContr         


        
相关标签:
2条回答
  • 2020-12-03 20:36

    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
    }
    
    0 讨论(0)
  • 2020-12-03 20:42

    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"
                }
    
    0 讨论(0)
提交回复
热议问题