当用户点击标签栏中的标签栏项目时,我想实现滚动到 View Controller 的顶部。我通过覆盖 tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool
来做到这一点UITabBarControllerDelegate
中的方法.
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
// Scroll to top only if we are already on given tab
if viewControllers?.firstIndex(of: viewController) == selectedIndex {
// Checks if root VC of navigation controller is currently shown and then scrolls it to top
scrollToTop(at: selectedIndex)
}
return true
}
每个选项卡都有导航 Controller 作为其 View Controller ,点击选项卡栏会弹出到 Root View Controller 。这很好,也很理想,但我想要双击工作,即用户在导航 Controller 的第二个(或以后) View 中,双击标签栏,然后导航 Controller 弹出, Root View Controller 滚动到顶部(第一次点击弹出到 Root View Controller 和第二个滚动到顶部)。
不幸的是,当这种情况发生时,这个委托(delegate)方法只被调用一次。只有在弹出过渡结束后,它才会开始检测标签栏项目上的下一次点击。
切换标签时双击可以正常工作,即用户在标签 B 上,双击标签 A,然后第一次点击切换到标签 A,第二次滚动使其滚动到顶部。
我检查了 Facebook 和 Twitter 应用程序,它们都正确地处理了快速双击——它们弹出然后滚动到顶部。
有没有办法在弹出转换正在进行时检测标签栏项目的点击?我尝试覆盖
tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)
的 UITabBarController
但在上述情况下,它也不会在双击时被调用两次。添加自定义双击识别器也无济于事,因为它会显着延迟单击标签栏,从而导致应用程序看起来滞后。
最佳答案
您可以尝试在这种情况下使用通知。
首先,为 Notification.Name 创建扩展名:
extension Notification.Name {
static var userDoubleTapTabbar: Notification.Name {
return .init(rawValue: "User.DoubleTapTabbar")
}
}
然后,在您的标签栏 Controller 中,检测您的用户双击项目事件并触发通知:
public var lastTabbarItem: UITabBarItem?
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
SEManager.shared.playSound(type: .tap_bottom_tap)
if self.lastTabbarItem == item {
NotificationCenter.default.post(name: .userDoubleTapTabbar, object: nil)
}
self.lastTabbarItem = item
}
然后在您的 Tabbar 项目 View Controller 中,您可以为该通知添加观察者和处理程序,以将您的表格 View 滚动到顶部。您可以使用它来检查该 Tabbar 项目 View Controller 是否当前可见:
if viewController.viewIfLoaded?.window != nil {
// viewController is visible
}
希望它对我的糟糕英语有帮助和抱歉。
关于ios - 当第一个触发popToRootViewController时检测标签栏项目上的第二次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053262/