相同的视图控制器在选项卡栏控制器的4个选项卡是给出错误的选定的选项卡控制器选定的索引
问题描述:
我想为我的应用程序做一个模板...可以说我的应用程序加载相同的视图控制器有一个CollectionView的4选项卡。根据选定的索引,我必须将内容加载到收集视图中。我从Appdelegate手动设置标签栏。我的问题是这可能像实例化一次Tabbarcontroller的所有4个选项卡相同viewgentroller。如果是的话,我将如何正确地知道选择了哪个索引?相同的视图控制器在选项卡栏控制器的4个选项卡是给出错误的选定的选项卡控制器选定的索引
代码tabBarcontroller中的appdelegate
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let tabBarController = UITabBarController()
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let firstImage = UIImage(named: "image1")
let secondImage = UIImage(named: "image2")
var controllers = [UIViewController]()
for var i = 0; i < self.myList.count; i++ {
let vc : ViewControllerTwo = storyboard.instantiateViewControllerWithIdentifier("view1") as! ViewControllerTwo
if(i == 0 || i == 3)
{
vc.tabBarItem = UITabBarItem(
title: self.myList[i],
image: firstImage,
tag: i)
controllers.append(vc)
}
else
{
vc.tabBarItem = UITabBarItem(
title: self.myList[i],
image: secondImage,
tag: i)
controllers.append(vc)
}
}
self.tabBarController.viewControllers = controllers
self.window?.rootViewController = self.tabBarController
self.self.window?.rootViewController = self.tabBarController
self.window?.makeKeyAndVisible()
答
如果你设置你的类为代表您的标签栏控制器,你会得到的didSelectViewController
委托方法的调用。然后,您可以使用您的controllers
阵列来确定索引;
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let tabBarController = UITabBarController()
tabBarController.delegate = self
func tabBarController(_ tabBarController: UITabBarController,
didSelectViewController viewController: UIViewController) {
if let index = self.controllers.indexOf(viewController) {
// Do something with index
}
}
我想我解决它使用了一个的NSTimer方法,有时变化并获得国家给予如下描述状态不好 http://stackoverflow.com/questions/28099148/switch-tab-bar- programatically-in-swift – Saty
您应该将您的类设置为标签栏控制器的代理,然后您将调用'didSelectViewController'。您可以将选定的视图控制器与'controllers'数组进行比较,以确定所选视图控制器的索引 – Paulw11
除非您做错什么,否则您不应该需要NSTimer ... – Paulw11