Tap tab bar to scroll to top of UITableViewController

后端 未结 12 931
面向向阳花
面向向阳花 2020-12-23 10:15

Tapping the tab bar icon for the current navigation controller already returns the user to the root view, but if they are scrolled way down, if they tap it again I want it t

12条回答
  •  时光说笑
    2020-12-23 10:50

     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: self.view)
        }
    
    }
    

    This is my answer in Swift 3. It uses a helper function for recursive calls and it automatically scrolls to top on call. Tested on a UICollectionViewController embedded into a UINavigationController embedded in a UITabBarController

提交回复
热议问题