Far*_*ris 35 uitabbarcontroller ios swift
如何用swift设置标签栏徽章?例如,当我收到消息图标上显示数字1的新消息时!我是否必须使用UITabBarItem.swift并在其中编写代码!我不确定我怎么做
谢谢 !
Lep*_*ron 88
如果您获得了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"
}
Run Code Online (Sandbox Code Playgroud)
从UITabBarController它将tabBar.items
代替tabBarController?.tabBar.items
并删除徽章:
tabItem.badgeValue = nil
Run Code Online (Sandbox Code Playgroud)
Rup*_*pom 16
以下行可以帮助您在UITabBerItem中显示徽章
tabBarController?.tabBar.items?[your_desired_tabBer_item_number].badgeValue = value
Run Code Online (Sandbox Code Playgroud)
小智 9
如果需要,还可以为徽章值设置一个空字符串以获得红色圆圈:
tabBarController?.tabBar.items?.last?.badgeValue = ""
Run Code Online (Sandbox Code Playgroud)
设置badgeValue
在ViewDidAppear
. 否则它可能不会从应用加载中出现。
import UIKit
class TabBarController: UITabBarController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tabBar.items![2].badgeValue = "7"
}
}
Run Code Online (Sandbox Code Playgroud)
没有安全检查,因为您通常确定您有TabBar
n 个选项卡。
小智 6
我将 @Victor 代码放入扩展中,以使代码在视图中更小。
\nimport UIKit\n\nextension UITabBar {\n func addBadge(index:Int) {\n if let tabItems = self.items {\n let tabItem = tabItems[index]\n tabItem.badgeValue = "\xe2\x97\x8f"\n tabItem.badgeColor = .clear\n tabItem.setBadgeTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)\n }\n }\n func removeBadge(index:Int) {\n if let tabItems = self.items {\n let tabItem = tabItems[index]\n tabItem.badgeValue = nil\n }\n }\n \n }\n\n\nApplication: \n\n tabBarController?.tabBar.addBadge(index: 1)\n\n tabBarController?.tabBar.removeBadge(index: 1)\n\n\n\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
21862 次 |
最近记录: |