Ios 访问TabBarController
我有一个带有5个图标的TabBarController。在所有5个ViewController中,我都有冗余代码来更新TabBarController的徽章Ios 访问TabBarController,ios,swift,Ios,Swift,我有一个带有5个图标的TabBarController。在所有5个ViewController中,我都有冗余代码来更新TabBarController的徽章 func updateBadges(tabBarController : UITabBarController) { (tabBarController!.tabBar.items![0] as! UITabBarItem).badgeValue = getBadgeValueFor(0) (tabBarController!.tabBar
func updateBadges(tabBarController : UITabBarController) {
(tabBarController!.tabBar.items![0] as! UITabBarItem).badgeValue = getBadgeValueFor(0)
(tabBarController!.tabBar.items![1] as! UITabBarItem).badgeValue = getBadgeValueFor(1)
(tabBarController!.tabBar.items![3] as! UITabBarItem).badgeValue = getBadgeValueFor(3)
(tabBarController!.tabBar.items![4] as! UITabBarItem).badgeValue = getBadgeValueFor(4)}
这是我的冗余代码:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.latestTableOverView.reloadData()
// Update the badge:
self.updateBadges()
}
func updateBadges() {
(tabBarController!.tabBar.items![0] as! UITabBarItem).badgeValue = getBadgeValueFor(0)
(tabBarController!.tabBar.items![1] as! UITabBarItem).badgeValue = getBadgeValueFor(1)
(tabBarController!.tabBar.items![3] as! UITabBarItem).badgeValue = getBadgeValueFor(3)
(tabBarController!.tabBar.items![4] as! UITabBarItem).badgeValue = getBadgeValueFor(4)
}
getBadgeValueFor
是我的helper.swift
文件中的一个函数:
import UIKit
import Foundation
func getBadgeValueFor(wich: Int) -> String? {
// calculating the badge here...
}
:
// more stuff here
为了减少代码冗余,我想将
updateBadges
也移到我的助手类中。但是从那里,我无法访问Tabbar控制器。因此,如果我只是简单地将funupdateBadges
复制到我的助手文件中,它将不起作用 在helper类中创建一个函数,该函数将viewController
实例作为参数。
然后从视图控制器调用该函数,并将self作为参数。
在helper类的函数中,您可以从viewController
实例访问tabBarController
助手类:
func update_badge(vc : ViewController)
{
vc.tabBarController .../// access like this
}
*代码可能有语法错误
func updateBadges(tabBarController : UITabBarController) {
(tabBarController!.tabBar.items![0] as! UITabBarItem).badgeValue = getBadgeValueFor(0)
(tabBarController!.tabBar.items![1] as! UITabBarItem).badgeValue = getBadgeValueFor(1)
(tabBarController!.tabBar.items![3] as! UITabBarItem).badgeValue = getBadgeValueFor(3)
(tabBarController!.tabBar.items![4] as! UITabBarItem).badgeValue = getBadgeValueFor(4)}
UITabBarControllerDelegate
,并在tabBarController:didSelectViewController:
方法中调用更新徽章方法。
但是,您仍然需要在委托类中保留对选项卡栏控制器的引用,并将选项卡栏控制器作为参数传递给update badges方法static var myTabBarController : UITabBarController?
static func registerTabBarController(tbc : UITabBarController) {
myTabBarController = tbc}
static func updateBadges() {
(myTabBarController?.tabBar.items![0] as! UITabBarItem).badgeValue = getBadgeValueFor(0)
(myTabBarController?.tabBar.items![1] as! UITabBarItem).badgeValue = getBadgeValueFor(1)
(myTabBarController?.tabBar.items![3] as! UITabBarItem).badgeValue = getBadgeValueFor(3)
(myTabBarController?.tabBar.items![4] as! UITabBarItem).badgeValue = getBadgeValueFor(4)
}
可选调用确保即使未设置选项卡栏控制器对象,也不会崩溃。
对象和静态函数可以确保不必实例化帮助器