ios 如何快速设置标签栏徽章?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43111413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:02:01  来源:igfitidea点击:

How to set the tab bar badge with swift?

iosswiftuitabbarcontroller

提问by Faris

How to set the tab bar badge with swift ? for example when I get new message showing number 1 on the message icon ! Do I have to use the UITabBarItem.swift and write the code in it ! I'm not really sure how I can do it

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

Thank you !

谢谢 !

回答by Lepidopteron

If you got the reference to the tabBarController (e.g. from the UIViewController) you can do the following:

如果您获得了对 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"
}

From a UITabBarController it would be tabBar.itemsinstead of tabBarController?.tabBar.items

从 UITabBarController 它将tabBar.items代替tabBarController?.tabBar.items

and to delete the badge:

并删除徽章:

tabItem.badgeValue = nil

回答by Rupom

The following line may help you to show badge in UITabBerItem

以下行可以帮助您在 UITabBerItem 中显示徽章

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

回答by Denis Kutlubaev

Set badgeValuein ViewDidAppear. Otherwise it may not appear from app loading.

设置badgeValueViewDidAppear. 否则它可能不会从应用加载中出现。

import UIKit

class TabBarController: UITabBarController {

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

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

}

No safe checks since you are in general sure that you have TabBarwith n tabs.

没有安全检查,因为您通常确定您有TabBarn 个选项卡。

回答by Andres Paladines

Thanks to @Lepidopteron, instant solution for me. In addition, you can do it with the index of selected tab index:

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

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

Got the reference from thispost

这篇文章中得到了参考