问题描述
可能重复:
如何为 UIScrollView 启用方向锁定?
有没有办法让 UIScrollView 执行分页,例如仅水平滚动而不是垂直滚动?
Is there a way to have a UIScrollView perform paging e.g. only horizontally and not when scrolling vertically?
换句话说,我希望我的滚动视图在水平滚动时捕捉到页面边界,并在垂直滚动时自由滑动.
In other words, I want my scrollview to snap to page boundries when scrolling horizontally and free swiping when going vertically.
当然,简单的解决方案是使用两个 UIScrollView,每个方向一个,但在我的情况下这不是一个可行的解决方案.
Of course the trivial solution is using two UIScrollViews, one in each direction, but this is not a feasible solution in my case.
推荐答案
假设你总是想要在水平方向有任何移动时捕捉,并且只有在水平偏移没有改变的情况下才能自由滚动.
Presuming you always want snap if there is any movement in horizontal direction and free scrolling only if the horizontal offset has not changed.
- 设置 directionalLockEnabled = YES
- 将 UIScrollView 包裹在另一个向前触摸的视图中(因为我们将修改滚动视图的框架)
- 将 UIScrollView 的框架高度设置为 1(以便在处理水平滚动时最大限度地减少垂直对齐)
- 检测当前滑动的方向(在
scrollViewDidScroll:
中) - 如果 contentOffset 的 x 发生了变化,则设置 pagingEnabled = YES
- 如果只有 y 的 contentOffset 发生了变化,则设置 pagingEnabled = NO
这将模拟您想要的场景.如果您水平滑动页面将捕捉 - 由于成名高度设置为 1,垂直捕捉将最小化.
仅垂直滑动时,滚动视图将自由滚动.
This will simulate the scenario you want. If you swipe horizontally the page will snap - and the vertical snap will be minimal due to the fame height being set to 1.
When swiping only vertically, the scrollview will scroll freely.
这篇关于UIScrollView 单向分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!