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
How to set the tab bar badge with swift?
提问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.items
instead 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 badgeValue
in ViewDidAppear
. Otherwise it may not appear from app loading.
设置badgeValue
在ViewDidAppear
. 否则它可能不会从应用加载中出现。
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 TabBar
with n tabs.
没有安全检查,因为您通常确定您有TabBar
n 个选项卡。
回答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
从这篇文章中得到了参考