按秒滚动到顶部到栏项目

Scroll to the top by second tapped to Bar Item

当我第二次点击第一个 BarButtonItem(主页)时,我需要滚动到顶部。有很多答案,但其中 none 对我不起作用。这很不可思议,但确实如此。 我的 class 中有 UITabBarControllerDelegateviewDidLoad() 中有 self.tabBarController?.delegate = selfTableViewController 中有这个:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if self.tabBarController?.selectedIndex == 0 {
            self.tableView.setContentOffset(CGPoint(x: 0, y: -60), animated: true)
        }
    }

每次我点击主页(索引 = 0)时它都有效,但是当我已经在主屏幕上时我需要这样做(所有社交媒体的标准功能通过点击 [滚动到顶部 Feed =16=]).如果我上面有NavigationBar,如何设置Y坐标? 谢谢

您所要做的就是检查是否选择了 viewController 是您的视图控制器,它具有您需要滚动到顶部的 tableView。现在我建议使用滚动而不是设置内容偏移量,因为这可能会因设备和其他逻辑(例如大标题)而异

考虑到您拥有包含所有选项卡引用的自定义选项卡栏控制器,您可以这样做:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if viewController == myViewController {
            myViewController.tableView.scrollToRow(
                           at: IndexPath(row: 0, section: 0),
                           at: .top,
                           animated: true)
          }
        }
    }