0

I'm kinda stuck trying to implement a 'Scroll to top' function when I press a TabBarItem. What I made so far is a Frankenstein code I found on multiple stackoverflow posts, it works but only until a certain point.

This is what I did so far is:

class MainViewController: UITabBarController, UITabBarControllerDelegate

Set delegate to self

self.delegate = self

Override func tabBar

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    scrollToTop()
}

Extension for UIViewController

 extension UIViewController {
func scrollToTop() {
    func scrollToTop(view: UIView?) {
        guard let view = view else { return }

        switch view {
        case let scrollView as UIScrollView:
            if scrollView.scrollsToTop == true {
                scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: true)
                return
            }
        default:
            break
        }

        for subView in view.subviews {
            scrollToTop(view: subView)
        }
    }

    scrollToTop(view: view)
}

}

This is where I'm stuck currently: Whenever I press a TabBarItem i get scrolled back to top. I would like to get the top. I would like to get scrolled back to the top only if I press TabBarItem that shows the current view, keep the current state of the view when I change tabs.

Sizzle
  • 93
  • 1
  • 4
  • Why don’t you scroll to 0,0 ? – Ptit Xav Jul 12 '22 at 16:32
  • @ptitXav Thanks for the reply but the result is the same, I would like to know basically what I need to add to func tabBar in order to scroll top only when I press the TabBarItem that presents the view I'm currently on. – Sizzle Jul 12 '22 at 16:38

1 Answers1

1

In your subclassed UITabBarController you can override didSelect item:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    // get the index of the item
    if let idx = tabBar.items?.firstIndex(of: item) {
        // if it is equal to selectedIndex,
        //  we tapped the current tab
        if idx == selectedIndex {
            print("same tab")

            // call your scroll to top func
            scrollToTop()

        }
    }
}
DonMag
  • 69,424
  • 5
  • 50
  • 86