简体   繁体   English

标签栏单击以滚动到顶部表格视图

[英]Tab bar click to scroll to top table view

I am using this View hierarchy.我正在使用这个视图层次结构。

UITabBarController > UINavigationController > UITableViewController -> UIViewController (On click of any table cell) UITabBarController > UINavigationController > UITableViewController -> UIViewController (点击任何表格单元格)

I want to scroll to top of the list on clicking the tab bar item that is currently selected.我想在单击当前选择的标签栏项目时滚动到列表顶部。 How can I achieve this?我怎样才能做到这一点? Thanks in advance.提前致谢。

First you need to declare a protocol首先你需要声明一个协议

protocol RefreshProtocol {
    func scrollToTopRefresh()
}

then what you need to do is to write delegate method of your custom tabBar Controller那么您需要做的是编写自定义tabBar Controller 的委托方法

  class MainViewController: UITabBarController {}

    extension MainViewController: UITabBarControllerDelegate {
        func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

            if tabBarController.selectedViewController == viewController {
                if let navController = viewController as? UINavigationController {
                    if let myViewController  = navController.topViewController , let homeController = myViewController as? RefreshProtocol {
                        homeController.scrollToTopRefresh()
                    }
                }
                else {
                   if let homeController = viewController as? RefreshProtocol {
                        homeController.scrollToTopRefresh()
                    }
                }
            }
        } 

Whichever class confirm refresh protocol will implement this function like this无论哪个 class 确认刷新协议都会像这样实现这个 function

class HomeViewController:UIViewController{}

extension HomeViewController:RefreshProtocol {
    func scrollToTopRefresh () {

                    let indexPath = IndexPath(row: 0, section: 0)
                    self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                }
            }
    }

}

Add this to the target of your button将此添加到按钮的目标

tableView.scrollsToTop = true
tableView.clipsToBounds = true
self.tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM