UIScrollView paging in single direction [duplicate

2020-02-12 07:55发布

Possible Duplicate:
How do I enable directional lock for a 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.

Of course the trivial solution is using two UIScrollViews, one in each direction, but this is not a feasible solution in my case.

1条回答
淡お忘
2楼-- · 2020-02-12 08:48

Presuming you always want snap if there is any movement in horizontal direction and free scrolling only if the horizontal offset has not changed.

  1. Set directionalLockEnabled = YES
  2. Wrap the UIScrollView in another view which forwards touches (as we will modify the scrollview's fram`e)
  3. Set the UIScrollView's frame height to 1 (in order to minimize vertical snapping when handling horizontal scroll)
  4. Detect the direction of the current swipe (in scrollViewDidScroll:)
  5. If x of contentOffset has changed, then set pagingEnabled = YES
  6. If only y of contentOffset has changed, then set pagingEnabled = NO

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.

查看更多
登录 后发表回答