点击标签栏时将桌面视图滚动到顶部

Phy*_*ber 1 uitableview tableview ios swift

选择标签栏项时,我需要一直向上滚动表格视图.我试过这个,但它不起作用.

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    let tabBarIndex = tabBarController.selectedIndex
    if tabBarIndex == 0 {

        let indexPath = NSIndexPath(row: 0, section: 0)
        MyViewController().tableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
    }
}
Run Code Online (Sandbox Code Playgroud)

调用该方法但tableView不会滚动到顶部.

Rya*_*los 5

问题是你正在创建一个新MyViewController实例,而不是访问屏幕上的实例.您将要访问已创建的viewController,幸运的是,此委托方法将此权交给您.

改变这一行

MyViewController().tableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
Run Code Online (Sandbox Code Playgroud)

let myViewController = viewController as? MyViewController
myViewController.tableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
Run Code Online (Sandbox Code Playgroud)