Reputation: 939
So I have a viewController
with a tableView
that is being presented from a tabBarController
. If the user taps the tabBarItem
for the view that is already being shown, I want the tableView
to scroll to the top. I have set the UITabBarControllerDelegate
to be the viewController
and then added the following method:
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.selectedIndex == 0 {
//scroll to the top!
}
}
The problem is that the tableView
scrolls to the top regardless of the current view. So I tried to add a second condition that makes sure that the currently displayed view is the correct one but nothing seemed to be correct.
TL;DR
How can I tell that the user is tapping on the tabBarItem
that is already selected?
Upvotes: 2
Views: 349
Reputation: 2465
You can use self.view.window != nil
to determine if the view of the vc is already displayed. Use shouldSelect
delegate method, which is called before the selection.
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
}
Upvotes: 3