ios - 带有 UIAlertAction swift 的增量标签栏角标(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)"

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

每次用户选择"is"时,我希望它递增 1。现在显然它只停留在 1。

最佳答案

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

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 swift 的增量标签栏角标(Badge)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688008/

相关文章:

ios - 如何使用 Swift 将通知数据传递给 View Controller

swift - TableView 单元格,在哪里设置所选单元格的样式?

ios - 如何在 ios swift 中制作可滚动的标签栏?

ios - 触摸并按住 TableViewCell 以显示(工具提示)弹出窗口在 iPhone 中是否可行?

iphone - 如何使用GPUImage框架复制CIRandomGenerator

ios - 如何不使用标签方法访问UIView

ios - 使用 iOS App、Swift 获取设备/用户位置的问题

ios - 无法接收 remoteControlReceivedWithEvent - objective-c - ios

ios - swift 中的自定义集合 : is it a right way?

ios - 表达式过于复杂,无法在合理的时间内解决;考虑将表达式分解为不同的子表达式?