Tap tab bar to scroll to top of UITableViewController

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

    Swift 5: no need for stored properties in the UITabBarController.

    In MyTabBarController.swift, implement tabBarController(_:shouldSelect) to detect when the user re-selects the tab bar item:

    protocol TabBarReselectHandling {
        func handleReselect()
    }
    
    class MyTabBarController: UITabBarController, UITabBarControllerDelegate {
        override func viewDidLoad() {
            super.viewDidLoad()
            delegate = self
        }
    
        func tabBarController(
            _ tabBarController: UITabBarController,
            shouldSelect viewController: UIViewController
        ) -> Bool {
            if tabBarController.selectedViewController === viewController,
                let handler = viewController as? TabBarReselectHandling {
                // NOTE: viewController in line above might be a UINavigationController,
                // in which case you need to access its contents
                handler.handleReselect()
            }
    
            return true
        }
    }
    

    In MyTableViewController.swift, handle the re-selection by scrolling the table view to the top:

    class MyTableViewController: UITableViewController, TabBarReselectHandling {
        func handleReselect() {
            tableView?.setContentOffset(.zero, animated: true)
        }
    }
    

    Now you can easily extend this to other tabs by just implementing TabBarReselectHandling.

提交回复
热议问题