【问题标题】:How to tell if TabBarItem is already Selected如何判断 TabBarItem 是否已被选中
【发布时间】:2018-08-03 22:01:16
【问题描述】:

所以我有一个viewController 和一个tableView,它是由tabBarController 提供的。如果用户点击tabBarItem 来查看已经 正在显示的视图,我希望tableView 滚动到顶部。我已将UITabBarControllerDelegate 设置为viewController,然后添加以下方法:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    if tabBarController.selectedIndex == 0 {
        //scroll to the top!
    }
}

问题是tableView 滚动到当前视图的顶部不管。所以我尝试添加第二个条件,以确保当前显示的视图是正确的,但似乎没有什么是正确的。

TL;DR

如何判断用户正在点击已选中的tabBarItem

【问题讨论】:

  • 你在func tabBarController(...)前面写过override吗?
  • @AlexandreFenyo 不,我认为它不需要那个。我可以确认该函数正在被调用,我遇到了函数内部应该包含什么的问题

标签: ios swift uitabbarcontroller uitabbar uitabbaritem


【解决方案1】:

您可以使用self.view.window != nil 来确定vc 的视图是否已经显示。使用shouldSelect委托方法,在选择之前调用。

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {



    if viewController === self && self.isViewLoaded {

    // Please use viewController === self.navigationController
    // if self is a child of a UINavigationController. We should
    // compare the viewController with a direct child of the 
    // UITabController

        if self.view.window != nil {
            print("scroll to top")
        } else {
            print("Don't scroll to top")
        }
    }
    return true
}

【讨论】:

  • 我喜欢使用shouldSelect而不是didSelect的想法,但是这里仍然存在逻辑错误。添加这两行代码时:print(self.isViewLoaded) print(viewController === self) 我发现它总是打印 truefalse
  • 出于某种原因viewController === self(或类似viewController == self)总是返回false
  • 我猜你的vc有一个导航控制器。在这种情况下,您应该使用 (viewController === self.navigationController)。我们要比较标签栏控制器的直接子级。你应该使用 ===,因为你要确保有两个指针指向同一个视图控制器。
  • @MattBart 对不起,我忘了@你
  • 太棒了,这是我一直在寻找的错误?!关于您的答案的一件事是,我必须添加 tabBarController.selectedIndex == 0 因为视图由 tabBarController 控制,即使您正在查看不同的选项卡,它们仍然会被加载,因此 self.isViewLoaded 始终是正确的。所以我的语句看起来像这样:if viewController === self.navigationController && tabBarController.selectedIndex == 0 { 即使用户从另一个选项卡中选择了选项卡,您拥有的 if 语句也是 true
猜你喜欢
  • 2011-05-19
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
  • 2016-01-04
  • 2017-03-29
  • 2011-10-12
  • 1970-01-01
  • 2015-06-11
相关资源
最近更新 更多