如何判断TabBarItem是否已被选中

时间:2018-08-03 22:01:17

标签: ios swift uitabbarcontroller uitabbar uitabbaritem

因此,我有一个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

1 个答案:

答案 0 :(得分:2)

您可以使用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
}
相关问题