如何使用 Swift 设置选项卡栏徽章?例如,当我收到新消息时,在消息图标上显示数字 1!我需要使用 UITabBarItem.swift 并在其中编写代码吗?我不太确定该如何实现。
谢谢!
如何使用 Swift 设置选项卡栏徽章?例如,当我收到新消息时,在消息图标上显示数字 1!我需要使用 UITabBarItem.swift 并在其中编写代码吗?我不太确定该如何实现。
谢谢!
如果您从UIViewController获取了对tabBarController的引用,您可以执行以下操作:
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
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)
let tabItems = self.tabBarController?.tabBar.items as NSArray!
var selectedIndex = tabBarController!.selectedIndex //here
let tabItem = tabItems![selectedIndex] as! UITabBarItem
tabItem.badgeValue = "2"
func showHideInnerBagde(value:String,indexValue:Int) {
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let sceneDelegate = windowScene.delegate as? SceneDelegate,
let navController = sceneDelegate.window?.rootViewController as? UINavigationController,
let visibleController = navController.visibleViewController,
let tabbarController = visibleController as? UITabBarController,
tabbarController.tabBar.items?.indices.contains(2) ?? false {
let tabIndex = indexValue
tabbarController.tabBar.items?[tabIndex].badgeValue = value
tabbarController.tabBar.items?[tabIndex].badgeColor = UIColor.clear
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: UIColor.red,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12) // Set your desired font
]
tabbarController.tabBar.items?[tabIndex].setBadgeTextAttributes(attributes, for: .normal)
} else {
// Handle the case when the conditions are not met or the tab at index 2 does not exist.
print("Unable to set badge value and text attributes.")
}
}