【问题标题】:Programmatically get index of a ViewController in the TabBar以编程方式获取 TabBar 中 ViewController 的索引
【发布时间】:2012-07-12 20:04:29
【问题描述】:

如何从视图控制器文件中以编程方式获取视图控制器标签栏中的索引(最左边的标签从 0 开始)。

我正在用这个切换视图:

[self.tabBarController setSelectedIndex:nextIndex];

我希望能够设置:

int nextIndex = currentIndex++;

如何获得当前索引?

编辑:以下三个答案都是正确的,谢谢大家。公平地说,我会选择最先发布的那个。

【问题讨论】:

    标签: ios tabview


    【解决方案1】:

    获取选定的索引:

    NSUInteger selectedIndex = self.tabBarController.selectedIndex;
    

    获取当前 ViewController 的索引(从 VC 中):

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

    设置索引:

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

    【讨论】:

    • 太棒了!前两种解决方案是否比另一种更好或更安全?
    • 取决于你的用例:第一个给你当前选择的索引; second 为您提供(询问)视图控制器的索引。
    • 啊,谢谢你的澄清。那我就用第二个。
    【解决方案2】:

    可以通过selectedIndex属性获取tabController的当前索引:

    [self.tabBarController selectedIndex]
    

    此外,如果您想获取 ViewController 的索引,您可以使用属性viewControllers 访问选项卡的数组。

    查看 Apple doc 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多