Tap tab bar to scroll to top of UITableViewController

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

    SWIFT 3

    Here goes..

    First implement the UITabBarControllerDelegate in the class and make sure the delegate is set in viewDidLoad

    class DesignStoryStreamVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITabBarControllerDelegate {
    
     @IBOutlet weak var collectionView: UICollectionView!
    
     override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tabBarController?.delegate = self
    
            collectionView.delegate = self
            collectionView.dataSource = self
        }
    }
    

    Next, put this delegate function somewhere in your class.

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    
        let tabBarIndex = tabBarController.selectedIndex
    
        print(tabBarIndex)
    
        if tabBarIndex == 0 {
            self.collectionView.setContentOffset(CGPoint.zero, animated: true)
        }
    }
    

    Make sure to select the correct index in the "if" statement. I included the print function so you can double check.

提交回复
热议问题