Stanislav Putilov
Stanislav Putilov

Reputation: 185

Scroll to the top by second tapped to Bar Item

I need to scroll to the top when I tapped second time to the first BarButtonItem (Home). There are a lot of answers but none of them don't work for me. It's incredible but it is. I have UITabBarControllerDelegate in my class, self.tabBarController?.delegate = self in viewDidLoad() and this in my TableViewController:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if self.tabBarController?.selectedIndex == 0 {
            self.tableView.setContentOffset(CGPoint(x: 0, y: -60), animated: true)
        }
    }

It works everytime I tapped to the Home (index = 0), but I need to do this when I'm already on the Home screen (standart function for all social media to scroll to the top Feed by tapping Home). And how to set Y coordinate if I have a NavigationBar above? Thanks

Upvotes: 0

Views: 78

Answers (1)

inokey
inokey

Reputation: 6190

All you have to do is check if selected viewController is your view controller that has tableView you need to scroll to top. Now I'd recommend using scroll to instead of setting content offset because that may vary based on the device and other logic (like large title for example)

Considering you have your custom tab bar controller that has all the tabs references you could do something like this:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if viewController == myViewController {
            myViewController.tableView.scrollToRow(
                           at: IndexPath(row: 0, section: 0),
                           at: .top,
                           animated: true)
          }
        }
    }

Upvotes: 1

Related Questions