【发布时间】:2020-06-15 10:29:57
【问题描述】:
我正在使用这个视图层次结构。
UITabBarController > UINavigationController > UITableViewController -> UIViewController(点击任何表格单元格)
我想在单击当前选择的标签栏项目时滚动到列表顶部。 我怎样才能做到这一点?提前致谢。
【问题讨论】:
我正在使用这个视图层次结构。
UITabBarController > UINavigationController > UITableViewController -> UIViewController(点击任何表格单元格)
我想在单击当前选择的标签栏项目时滚动到列表顶部。 我怎样才能做到这一点?提前致谢。
【问题讨论】:
将此添加到按钮的目标
tableView.scrollsToTop = true
tableView.clipsToBounds = true
self.tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
【讨论】:
首先你需要声明一个协议
protocol RefreshProtocol {
func scrollToTopRefresh()
}
那么你需要做的就是编写自定义tabBar控制器的委托方法
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()
}
}
}
}
无论哪个类确认刷新协议都会这样实现这个功能
class HomeViewController:UIViewController{}
extension HomeViewController:RefreshProtocol {
func scrollToTopRefresh () {
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
}
}
【讨论】: