菜鸟教程小白 发表于 2022-12-11 18:06:16

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


                                            <p><pre><code>@IBAction func addToCart(sender: AnyObject) {
    let itemObjectTitle = itemObject.valueForKey(&#34;itemDescription&#34;) as! String
    let alertController = UIAlertController(title: &#34;Add \(itemObjectTitle) to cart?&#34;, message: &#34;&#34;, preferredStyle: .Alert)
    let yesAction = UIAlertAction(title: &#34;Yes&#34;, style: UIAlertActionStyle.Default) { (action) in
    var tabArray = self.tabBarController?.tabBar.items as NSArray!
    var tabItem = tabArray.objectAtIndex(1) as! UITabBarItem
    let badgeValue = &#34;1&#34;
    if let x = badgeValue.toInt() {
      tabItem.badgeValue = &#34;\(x)&#34;
    }
}
</code></pre>

<p>我不知道为什么我不能只做 += "(x)"</p>

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

<p>我希望它在每次用户选择"is"时增加 1。现在显然它只是停留在 1。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可以尝试访问 badgeValue 并将其转换为 Integer,如下所示:</p>

<p><strong> swift2</strong></p>

<pre><code>if let badgeValue = tabBarController?.tabBar.items?.badgeValue,
    nextValue = Int(badgeValue)?.successor() {
    tabBarController?.tabBar.items?.badgeValue = String(nextValue)
} else {
    tabBarController?.tabBar.items?.badgeValue = &#34;1&#34;
}
</code></pre>

<p><strong>Swift 3 或更高版本</strong></p>

<pre><code>    if let badgeValue = tabBarController?.tabBar.items?.badgeValue,
      let value = Int(badgeValue) {
      tabBarController?.tabBar.items?.badgeValue = String(value + 1)
    } else {
      tabBarController?.tabBar.items?.badgeValue = &#34;1&#34;
    }
</code></pre>

<p>要删除角标(Badge),只需将 nil 分配给 badgeValue 覆盖 viewDidAppear 方法:</p>

<pre><code>override func viewDidAppear(animated: Bool) {
    tabBarController?.tabBar.items?.badgeValue = nil
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 使用 UIAlertAction 快速增加标签栏角标(Badge)?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40688008/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40688008/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 使用 UIAlertAction 快速增加标签栏角标(Badge)?