Ios 如何使用swift设置标签栏徽章?

Ios 如何使用swift设置标签栏徽章?,ios,swift,uitabbarcontroller,Ios,Swift,Uitabbarcontroller,如何使用swift设置标签栏徽章?例如,当我收到消息图标上显示数字1的新消息时! 我是否必须使用uitabaritem.swift并在其中编写代码! 我真的不知道该怎么做 谢谢大家! 如果您获得了对tabBarController的引用(例如从UIViewController),则可以执行以下操作: if let tabItems = tabBarController?.tabBar.items { // In this case we want to modify the badge

如何使用swift设置标签栏徽章?例如,当我收到消息图标上显示数字1的新消息时! 我是否必须使用uitabaritem.swift并在其中编写代码! 我真的不知道该怎么做


谢谢大家!

如果您获得了对tabBarController的引用(例如从UIViewController),则可以执行以下操作:

if let tabItems = tabBarController?.tabBar.items {
    // In this case we want to modify the badge number of the third tab:
    let tabItem = tabItems[2]
    tabItem.badgeValue = "1"
}

从UITabBarController,它将是
tabBar.items
,而不是
tabBar控制器?.tabBar.items

以及删除徽章:

tabItem.badgeValue = nil

以下行可能有助于您在UITabBerItem中显示徽章

tabBarController?.tabBar.items?[your_desired_tabBer_item_number].badgeValue = value

感谢@Lepidopteron,我的即时解决方案。 此外,您还可以使用所选选项卡索引的索引执行此操作:

let tabItems = self.tabBarController?.tabBar.items as NSArray!
    var selectedIndex = tabBarController!.selectedIndex //here 
    let tabItem = tabItems![selectedIndex] as! UITabBarItem
    tabItem.badgeValue = "2"

viewdide
中的post

设置
badgeValue
获取参考。否则,它可能不会从应用程序加载中显示

import UIKit

class TabBarController: UITabBarController {

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.tabBar.items![2].badgeValue = "7"
}

}

没有安全检查,因为一般情况下,您肯定有带有n个选项卡的
TabBar

如果需要,还可以为徽章值设置空字符串以获得红色圆圈:

tabBarController?.tabBar.items?.last?.badgeValue = ""

我将@Victor代码放在一个扩展中,以使代码在视图中更小

导入UIKit
阿巴尔延伸{
func addBadge(索引:Int){
如果让tabItems=self.items{
设tabItem=tabItems[索引]
tabItem.badgeValue=”●"
tabItem.badgeColor=.clear
tabItem.setBadgeTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.red],用于:。正常)
}
}
func removeBadge(索引:Int){
如果让tabItems=self.items{
设tabItem=tabItems[索引]
tabItem.badgeValue=nil
}
}
}
应用程序:
tabBar控制器?.tabBar.addBadge(索引:1)
tabBar控制器?.tabBar.removeBadge(索引:1)

tabBar控制器?.tabBar.items?[4].badgeValue=“1“你能解释一下密码吗?什么是tabArray!你是从哪里得到tabArray的?我应该在哪里使用这段代码?在我的TabBarController内部或在与tabItem相对应的ViewController内部,例如我的通知选项卡..上面的答案应该是从uiviewcontroller(嵌套在TabBarController中的任何ViewController)访问tabbar的元素。我已经扩展了它的外观,如果您在UITabBarController子类中有实现,我打算在具有TableView的aViewcontroller中使用它。并让徽章显示TableView中有多少个单元格请在代码中添加说明。只有代码的答案被认为是低质量的,经常被否决,甚至可能被删除。请参见1)tabBarController?-取消包装,因为我们实际上不知道它是否存在于我们的UIVewController 2).tabBar.items?-询问UITabBarController中选项卡栏中的一个项目数组,该数组也已展开,因为我们不知道该数组是否已使用至少一个UITabBarItem初始化3)。[UITabBarItem数组中的索引]4).badgeValue-要查看的UITabBarItem的badge的字符串值。