Tap tab bar to scroll to top of UITableViewController

后端 未结 12 1039
面向向阳花
面向向阳花 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:46

    I was using this View hierarchy.

    UITabBarController > UINavigationController > UIViewController


    I got a reference to the UITabBarController in the UIViewController

    tabBarControllerRef = self.tabBarController as! CustomTabBarClass
    tabBarControllerRef!.navigationControllerRef = self.navigationController as! CustomNavigationBarClass
    tabBarControllerRef!.viewControllerRef = self
    

    Then I created a Bool that was called at the correct times, and a method that allows scrolling to top smoothly

    var canScrollToTop:Bool = true
    
    // Called when the view becomes available
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        canScrollToTop = true
    }
    
    // Called when the view becomes unavailable
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        canScrollToTop = false
    }
    
    // Scrolls to top nicely
    func scrollToTop() {
        self.collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
    }
    

    Then in my UITabBarController Custom Class I called this

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    
        // Allows scrolling to top on second tab bar click
        if (viewController.isKindOfClass(CustomNavigationBarClass) && tabBarController.selectedIndex == 0) {
            if (viewControllerRef!.canScrollToTop) {
                viewControllerRef!.scrollToTop()
            }
        }
    }
    

    The Result is identical to Instagram and Twitter's feed :)

提交回复
热议问题