OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 UIAlertAction 快速增加标签栏角标(Badge)? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:06
标题: ios - 使用 UIAlertAction 快速增加标签栏角标(Badge)?

@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。



Best Answer-推荐答案


您可以尝试访问 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 分配给 badgeValue 覆盖 viewDidAppear 方法:

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

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






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4