我可以在滚动位置停止 UIScrollView 吗?



我想在特定点到达UIScrollView滚动时停止滚动。

我认为它会通过下面的代码来解决。

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let scrollY: CGFloat = scrollView.contentOffset.y
    stopScrollViewIfNeeded(by: scrollY)
}
func stopScrollViewIfNeeded(by scrollY: CGFloat) {
    guard scrollY <= SpecificY else {
        return
    }
    scrollView.isScrollEnabled = false
}

但我错了。 因为禁用滚动时contentOffset.y为 0。

改进了我的功能,就像下面的代码一样,但它仍然没有按照我想要的方式工作。

func stopScrollViewIfNeeded(by scrollY: CGFloat) {
    guard scrollY <= SpecificY else {
        return
    }
    scrollView.setContentOffset(.init(x: 0, y: SpecificY), animated: false)
    scrollView.isScrollEnabled = false
    scrollView.isPagingEnabled = true
}

如何提高stopScrollViewIfNeeded()以按心所欲地工作?

只需将contentOffset设置为:

只需要获取您希望停止的偏移值并分配值,如下所示

水平滚动视图

UIView.animate(withDuration: 0.5) {
            self.MainScollView.contentOffset.x = self.view.frame.size.width*2
        }

垂直滚动视图

UIView.animate(withDuration: 0.5) {
                self.MainScollView.contentOffset.y = 90
            }

您可以在 didScroll 中覆盖滚动位置。didScroll中的逻辑可以有效地使滚动滚动保持所需的时间。

最新更新