ios - 使用 UIAlertAction 快速增加标签栏角标(Badge)?

标签 ios swift swift2 swift3 uitabbaritem

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

错误: 二元运算符“+=”不能应用于“String?”类型的操作数和“字符串”

我希望每次用户选择"is"时它都会增加 1。现在显然它只是停留在 1。

最佳答案

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

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

要删除角标(Badge),只需将 nil 分配给覆盖 viewDidAppear 方法的 badgeValue 即可:

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

关于ios - 使用 UIAlertAction 快速增加标签栏角标(Badge)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390056/

相关文章:

ios - 多个 View 中的手势

ios - 实现大量 "views"的 ScrollView 查找?

ios - 如何在iOS中查找用户

swift - 带有圆角的 UIButton 的子类(快速)

ios - 尝试为所有出现的 TextView 字符串着色

ios - 以特定方式将 String 转换为 NSAttributedString

ios - 钛的转化当量

ios - 通过代码添加时 UITextField 不起作用

ios - 如何从自定义 CollectionViewController 的 didSelectItemAtIndexPath 实例化 ViewController,它是 tableViewCell 的一部分

ios - 如何使用 ios 图表设置 x 轴标签