我有一个有5个图标的TabBarController。在所有5个ViewControllers中,我都有多余的代码来更新TabBarController的徽章。
这是我的冗余代码:
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移动到我的助手类。但从那以后,我无法访问tabBarController。因此,如果我简单地将有趣的updateBadges复制到我的助手文件中,它就不能工作了。
发布于 2015-08-18 07:24:02
UITabBarControllerDelegate,并在tabBarController:didSelectViewController:方法中调用update view方法。但是,您仍然需要在委托类中保留对选项卡条控制器的引用,并将选项卡条控制器作为参数传递给更新标记方法。如果是根视图,则必须注册来自父或应用程序委托的选项卡条控制器。
然后,可以对此对象执行所有更新。
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)
}可选调用确保即使没有设置选项卡条控制器对象,也不会崩溃。对象和静态函数确保不必实例化助手。
发布于 2015-08-18 06:56:42
在helper类中创建一个函数,该函数将viewController实例作为参数。然后从您的视图中,控制器以self作为参数调用该函数。在helper类中的函数中,可以从tabBarController实例访问viewController。
帮助者班:
func update_badge(vc : ViewController)
{
vc.tabBarController .../// access like this
}*代码可能有语法错误
https://stackoverflow.com/questions/32065399
复制相似问题