iosswiftuikitstoryboarduitabbaritem

When TabBarItem is pressed scroll back to top (for example like on Reddit app)


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.


Solution

  • 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()
    
            }
        }
    }