Ios 在Swift中更新未选择tabBarItem的徽章

Ios 在Swift中更新未选择tabBarItem的徽章,ios,swift,uitabbarcontroller,Ios,Swift,Uitabbarcontroller,我有一个带有4个选项卡栏项的导航控制器。每一个里面都有一个导航控制器。我希望在收到推送通知时能够更改第四个选项卡栏徽章编号,无论我在哪个视图或选项卡中。我需要使用自动布局,以便我不能在应用程序代理中使用任何编程解决方案。我从一个视图模板开始了这个项目 我试图转到所需的选项卡,更改徽章值并返回,但当然没有成功。 tabBarController似乎只有对当前选项卡栏项的引用 var current = self.tabBarController?.selectedIndex sel

我有一个带有4个选项卡栏项的导航控制器。每一个里面都有一个导航控制器。我希望在收到推送通知时能够更改第四个选项卡栏徽章编号,无论我在哪个视图或选项卡中。我需要使用自动布局,以便我不能在应用程序代理中使用任何编程解决方案。我从一个视图模板开始了这个项目

我试图转到所需的选项卡,更改徽章值并返回,但当然没有成功。 tabBarController似乎只有对当前选项卡栏项的引用

    var current = self.tabBarController?.selectedIndex
    self.tabBarController?.selectedIndex = 3
    self.navigationController?.tabBarItem.badgeValue = "34"
    self.tabBarController?.selectedIndex = current!

无需选择该索引即可更新徽章值。获取选项卡栏项目的数组。在索引处选择要更新的项,然后将其设置为标记值。请参见下面我为第四个选项卡栏项目所做的操作

    var current = self.tabBarController?.selectedIndex
    self.tabBarController?.selectedIndex = 3
    self.navigationController?.tabBarItem.badgeValue = "34"
    self.tabBarController?.selectedIndex = current!
Swift 5.0

if let items = self.tabBarController?.tabBar.items as NSArray? {
    let tabItem = items.object(at: 3) as! UITabBarItem
    tabItem.badgeValue = "34"
}
较短:

let tabItem = self.tabBarController?.tabBar.items![3]
let tabItem.badgeValue = "34"
你可以这样称呼它:

self.tabBarController?.increaseBadge(indexOfTab: 3, num: "34")

干净整洁!非常感谢你!我在Obj-C中看到,它是使用objectAtIndex(索引)完成的,但我找不到从何处调用它。再次感谢你@Kampai这需要如何修改才能在app delegate中执行徽章图标更新?我无法从那里执行self.tabBarController?@user2363025:您需要获取
rootViewController
以从
AppDelegate
更新徽章。像这样
让rootViewController=self.window?.rootViewController为!超级阿巴斯控制器!让tabArray=rootViewController?.tabBar.items作为NSArray!设tabItem=tabArray.objectAtIndex(1)为!UITabBarItem tabItem.badgeValue=“34”
@Kampai感谢您的回复。我尝试了您的代码,但出现了错误:无法将类型为“UINavigationController”(0x198395090)的值强制转换为指向以下行的“UITabBarController”:let rootViewController=self.window?.rootViewController as!超级阿巴斯控制器@user2363025是的,根据您的登录,如果您的案例是显示选项卡,那么您可以在visible controller的
viewDidLoad
方法中输入徽章更新代码(以答案形式编写)。并且始终最好使用“if let”:if let tabItem=self.tabBarController?.tabBar.items![3] {tabItem.badgeValue=34}