提问人:Sizzle 提问时间:7/12/2022 最后编辑:Sizzle 更新时间:7/13/2022 访问量:88
按下 TabBarItem 时,滚动回顶部(例如,在 Reddit 应用程序上)
When TabBarItem is pressed scroll back to top (for example like on Reddit app)
问:
当我按下 TabBarItem 时,我有点卡在尝试实现“滚动到顶部”功能。到目前为止,我所做的是我在多个 stackoverflow 帖子上找到的弗兰肯斯坦代码,它有效,但只在某个点之前有效。
到目前为止,我所做的是:
class MainViewController: UITabBarController, UITabBarControllerDelegate
将委托设置为 self
self.delegate = self
覆盖 func tabBar
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
scrollToTop()
}
UIViewController 扩展
extension UIViewController {
func scrollToTop() {
func scrollToTop(view: UIView?) {
guard let view = view else { return }
switch view {
case let scrollView as UIScrollView:
if scrollView.scrollsToTop == true {
scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: true)
return
}
default:
break
}
for subView in view.subviews {
scrollToTop(view: subView)
}
}
scrollToTop(view: view)
}
}
这就是我目前卡住的地方:每当我按下 TabBarItem 时,我都会滚动回顶部。我想得到顶部。只有当我按下显示当前视图的 TabBarItem 时,我才希望滚动回顶部,在更改选项卡时保持视图的当前状态。
答:
1赞
DonMag
7/13/2022
#1
在子类中,您可以覆盖:UITabBarController
didSelect item
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
// get the index of the item
if let idx = tabBar.items?.firstIndex(of: item) {
// if it is equal to selectedIndex,
// we tapped the current tab
if idx == selectedIndex {
print("same tab")
// call your scroll to top func
scrollToTop()
}
}
}
评论