如何用swift设置标签栏徽章?

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)

  • 请在您的代码中添加说明.仅代码答案被认为是低质量的,通常被低估,甚至可能被删除.请看[答案] (3认同)
  • 1)tabBarController? - 解包因为我们实际上并不知道它是否存在于我们的UIVewController 2).tabBar.items? - 询问tabBar中UITabBarController中的项目数组,也解包,因为我们不知道这个数组是否用至少一个UITabBarItem初始化3).[数组中的UITabBarItem索引] 4).badgeValue - UITabBarItem徽章的字符串值你想看到的. (2认同)

小智 9

如果需要,还可以为徽章值设置一个空字符串以获得红色圆圈:

tabBarController?.tabBar.items?.last?.badgeValue = ""
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


wzb*_*zon 7

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

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)

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


小智 6

我将 @Victor 代码放入扩展中,以使代码在视图中更小。

\n
import 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