【发布时间】:2017-08-23 23:56:54
【问题描述】:
如何使用 swift 设置标签栏徽章?例如,当我收到消息图标上显示数字 1 的新消息时! 我是否必须使用 UITabBarItem.swift 并在其中编写代码! 我不确定我该怎么做
谢谢!
【问题讨论】:
-
tabBarController?.tabBar.items?[4].badgeValue = "1"
标签: ios swift uitabbarcontroller
如何使用 swift 设置标签栏徽章?例如,当我收到消息图标上显示数字 1 的新消息时! 我是否必须使用 UITabBarItem.swift 并在其中编写代码! 我不确定我该怎么做
谢谢!
【问题讨论】:
标签: ios swift uitabbarcontroller
如果您获得了对 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 而不是 tabBarController?.tabBar.items
并删除徽章:
tabItem.badgeValue = nil
【讨论】:
以下行可以帮助您在 UITabBerItem 中显示徽章
tabBarController?.tabBar.items?[your_desired_tabBer_item_number].badgeValue = value
【讨论】:
在ViewDidAppear 中设置badgeValue。否则它可能不会从应用加载中出现。
import UIKit
class TabBarController: UITabBarController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tabBar.items![2].badgeValue = "7"
}
}
没有安全检查,因为您通常确定您有带有 n 个标签的 TabBar。
【讨论】:
我将@Victor 代码放在一个扩展中,以使代码在视图中更小。
import UIKit
extension UITabBar {
func addBadge(index:Int) {
if let tabItems = self.items {
let tabItem = tabItems[index]
tabItem.badgeValue = "●"
tabItem.badgeColor = .clear
tabItem.setBadgeTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)
}
}
func removeBadge(index:Int) {
if let tabItems = self.items {
let tabItem = tabItems[index]
tabItem.badgeValue = nil
}
}
}
Application:
tabBarController?.tabBar.addBadge(index: 1)
tabBarController?.tabBar.removeBadge(index: 1)
【讨论】:
感谢@Lepidopteron,为我提供即时解决方案。 另外,您可以使用所选标签索引的索引来做到这一点:
let tabItems = self.tabBarController?.tabBar.items as NSArray!
var selectedIndex = tabBarController!.selectedIndex //here
let tabItem = tabItems![selectedIndex] as! UITabBarItem
tabItem.badgeValue = "2"
从this 帖子中获得参考
【讨论】: