使用 UIAlertAction swift 增加标签栏徽章? [英] Increment tab bar badge w/ UIAlertAction swift?

查看:25
本文介绍了使用 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)"
    }
}

我不知道为什么我不能只做 += "(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'

我希望每次用户选择是"时它都会增加 1.现在显然它只是保持在 1.

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

推荐答案

您可以尝试访问badgeValue并将其转换为Integer,如下所示:

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 或更高版本

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

要删除徽章只需将 nil 分配给覆盖 viewDidAppear 方法的徽章值:

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

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

这篇关于使用 UIAlertAction swift 增加标签栏徽章?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆