Reputation: 1368
I need to scroll table view all the way up when selecting the tab bar item. I tried this but it does not work.
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let tabBarIndex = tabBarController.selectedIndex
if tabBarIndex == 0 {
let indexPath = NSIndexPath(row: 0, section: 0)
MyViewController().tableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
}
}
The method is called but the tableView does not scroll to the top.
Upvotes: 1
Views: 927
Reputation: 452
self.tableviewObject.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
Upvotes: -1
Reputation: 18551
The problem is you're creating a new MyViewController
instance rather than accessing the one on screen. You'll want to access the viewController already created and luckily the this delegate method hands that to you.
Change this line
MyViewController().tableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
to
let myViewController = viewController as? MyViewController
myViewController.tableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
Upvotes: 5