Recognize swipe gesture in UIView to scroll the scrollView using gesture-recognizer

大兔子大兔子 提交于 2019-12-03 21:30:28
user1686439

EDIT

I actually just learned about a much simpler solution: just add view.addGestureRecognizer(scrollView.panGestureRecognizer) to your viewDidAppear or viewDidLoad.

What this essentially does is take the scrollView's UIPanGestureRecognizer, a gesture recognizer that recognizes finger dragging and scrolls the scrollView's content, and gives it to the base view so it can recognize finger dragging and scroll the scrollView's content too.

So you don't need all the math and scrollRectToVisible as described below. Oh well, I think it's useful and fun to learn more about how UIScrollViews work!

OLD

To programmatically make the UIScrollView "scroll", use UIScrollView's scrollRectToVisible.

See Programmatically scroll a UIScrollView for more details and code syntax.

Basically, at any point in time, a UIScrollView's content subview is offset some amount from its frame.

It helps to understand the parts to a UIScrollView (esp. the content subview), like in this picture (feel free to ignore the purple UIImageView):

In the first image, the UIScrollView's content subview (red outline) is not offset from the UIScrollView's frame (assumed to be the same size as the visible screen) at all: both have the same top left corner at (0, 0).

In the second/middle image, the UIScrollView's content subview is now offset "up": the content subview's top left corner is at something like (0, -200) now, where (0, 0) is still the top left corner of the UIScrollView's frame.

Again, you can change the UIScrollView's content subview offset, and thus simulate a "scroll", using scrollRectToVisible, and the parameter animated: true.

Hint: to have the content scroll left (after the user swipes right-to-left) for example, you'd take the UIScrollView's current content offset's x coordinate (scrollView.contentOffset.x) and subtract the width of the UIScrollView (scrollView.frame.size.width) to it. So if the UIScrollView's current content offset (top-left corner) is (0, 0), the content offset (top-left corner) moves from (0-width, 0), and the content "moves" left.

Make your scroll view to the view's frame, but then set the content inset/offset, so that it only goes until the blue frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!