2012-07-12 55 views
1

如何以编程方式从View Controller文件中获取视图控制器的选项卡中的索引(从最左侧的选项卡开始,位于0)。以编程方式获取TabBar中ViewController的索引

我切换视图与此:

[self.tabBarController setSelectedIndex:nextIndex]; 

,我希望能够给刚刚成立:

int nextIndex = currentIndex++; 

我怎样,目前的指数?

编辑:下面的答案都是正确的,谢谢你们。为了公平起见,我会选择首先发布的。

回答

6

获取选定的索引:

NSUInteger selectedIndex = self.tabBarController.selectedIndex; 

获得(来自VC中)当前视图控制器的指标:

NSUInteger selectedIndex = [self.tabBarController.viewControllers indexOfObject:self]; 

SET指数:

NSUInteger nextIndex = selectedIndex + 1; 
if(nextIndex < [self.tabBarController.viewControllers count]) 
    [self.tabBarController setSelectedIndex:nextIndex]; 
+0

非常好!前两种解决方案中哪一种比另一种解决方案更好或更安全? – Orchid 2012-07-12 20:12:40

+0

取决于你的用例:第一个给你当前选择的索引;第二个给你(问)视图控制器的索引。 – cweinberger 2012-07-12 20:13:42

+0

啊谢谢你的澄清。我会用第二个。 – Orchid 2012-07-12 20:15:38

0

您可以获得当前指数与属性selectedIndex tabController:

[self.tabBarController selectedIndex] 

另外,如果你想得到一个ViewController的索引,你可以访问属性为viewControllers的选项卡数组。

切苹果doc欲了解更多信息。