swift2 是否快速增加选项卡栏标记和UIAlertAction?

7ivaypg9  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(220)
@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?”与“String”类型得操作数
我希望每次用户选择“是”时它都增加1。现在显然它只是停留在1。

xdnvmnnf

xdnvmnnf1#

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

雨燕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方法的badgeValue:

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

zysjyyx42#

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

相关问题