Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to top UITableView with double tap on UITabBarItem

I want to simulate the behaviour of twitter or instagram in their list:

When double tap in UITabBarItem, the list is scrolling to top. Somebody knows how can I do this? I have 4 items in my UITabBarController, all of them are list, so I want to do this thing for all.

The problem is when I tap bar item in a push view of mi list, this function calls and detect double tap before get the root view controller of the navigation.

I hope can be clear with my problem.

var previousController: UIViewController?

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    if previousController == viewController{
        if let navVC = viewController as? UINavigationController, vc = navVC.viewControllers.first as? HomeViewController {
            vc.tableBusinessList.setContentOffset(CGPointZero, animated: true)
            print("same")
        }
    }else{
        print("No same")
    }
    previousController = viewController
}

The behaviour is no correct. When I pop the view with the tab bar item, the root view is on cell 0

enter image description here

like image 407
Dasoga Avatar asked May 09 '16 19:05

Dasoga


1 Answers

Ok so I think the best way to proceed is to check if the viewController with your tableView is visible, if it isn't, then don't call set content offset.

So:

var previousController: UIViewController?

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    if previousController == viewController {
        if let navVC = viewController as? UINavigationController, vc = navVC.viewControllers.first as? HomeViewController {

            if vc.isViewLoaded() && (vc.view.window != nil) {
                // viewController is visible
                vc.tableBusinessList.setContentOffset(CGPointZero, animated: true)
            }

            print("same")
        }
    }else{
        print("No same")
    }

    previousController = viewController

}
like image 57
Olivier Wilkinson Avatar answered Sep 21 '22 23:09

Olivier Wilkinson