Tap tab bar to scroll to top of UITableViewController

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

    In this implementation you no need static variable and previous view controller state

    If your UITableViewController in UINavigationController you can implement protocol and function:

    protocol ScrollableToTop {
        func scrollToTop()
    }
    
    extension UIScrollView {
        func scrollToTop(_ animated: Bool) {
            var topContentOffset: CGPoint
            if #available(iOS 11.0, *) {
                topContentOffset = CGPoint(x: -safeAreaInsets.left, y: -safeAreaInsets.top)
            } else {
                topContentOffset = CGPoint(x: -contentInset.left, y: -contentInset.top)
            }
            setContentOffset(topContentOffset, animated: animated)
        }
    }
    

    Then in your UITableViewController:

    class MyTableViewController: UITableViewController: ScrollableToTop {
       func scrollToTop() {
        if isViewLoaded {
            tableView.scrollToTop(true)
        }
       }
    }
    

    Then in UITabBarControllerDelegate:

    extension MyTabBarController: UITabBarControllerDelegate {
        func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
            guard tabBarController.selectedViewController === viewController else { return true }
            guard let navigationController = viewController as? UINavigationController else {
                assertionFailure()
                return true
            }
            guard
                navigationController.viewControllers.count <= 1,
                let destinationViewController = navigationController.viewControllers.first as? ScrollableToTop
            else {
                return true
            }
            destinationViewController.scrollToTop()
            return false
        }
    }
    

提交回复
热议问题