按下 TabBarItem 时,滚动回顶部(例如,在 Reddit 应用程序上)

When TabBarItem is pressed scroll back to top (for example like on Reddit app)

提问人:Sizzle 提问时间:7/12/2022 最后编辑:Sizzle 更新时间:7/13/2022 访问量:88

问:

当我按下 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 时,我才希望滚动回顶部,在更改选项卡时保持视图的当前状态。

iOS Swift UIKIT Storyboard UITABBARITEM

评论

0赞 Ptit Xav 7/13/2022
你为什么不滚动到 0,0 ?
0赞 Sizzle 7/13/2022
@ptitXav感谢您的回复,但结果是一样的,我想知道基本上我需要向 func tabBar 添加什么,以便仅在我按下显示我当前所在视图的 TabBarItem 时滚动顶部。

答:

1赞 DonMag 7/13/2022 #1

在子类中,您可以覆盖:UITabBarControllerdidSelect 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()

        }
    }
}