如何为 UIScrollView 启用方向锁定?
我有一个 UIScrollView
,里面有一个 UIView
。 我想锁定 x 轴,以便视图仅垂直滚动。 如何启用方向锁定?
I have a UIScrollView
with a UIView
inside. I want to lock the x-axis so that the view is only scrolled vertically. How do I enable directional locking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将继承
UIScrollView
并重写touchesBegan:withEvent:
方法、touchesMoved:withEvent:
方法和touchesEnded:withEvent : 方法。
您将使用这些方法以及触摸的起点和终点来计算发生的触摸事件类型:是简单的点击,还是水平或垂直滑动?
如果是水平滑动,则取消触摸事件。
请查看源代码,了解如何获得开始了。
You'll be subclassing
UIScrollView
and overriding thetouchesBegan:withEvent:
method,touchesMoved:withEvent:
method, and thetouchesEnded:withEvent:
method.You'll use those methods, along with the start and end points of a touch, to calculate what kind of touch event took place: was it a simple tap, or a horizontal or vertical swipe?
If it is a horizontal swipe, you cancel the touch event.
Take a look at the source code here to learn how you might get started.
首先,将
UIScrollView
的contentSize
设置为等于或小于 UIScrollView 框架的宽度。接下来,将 UIScrollView 的
alwaysBounceHorizontal
设置为 NO。 这将防止滚动视图出现“橡皮筋”,即使您已经告诉它没有更多的水平内容可以显示。滚动视图内的实际内容并不重要。
斯威夫特5.0
First, set the
UIScrollView
'scontentSize
to have a width that is equal to or less than the width of the UIScrollView's frame.Next, set
UIScrollView's
alwaysBounceHorizontal
to NO. This will prevent the scroll view from "rubber banding" even though you've told it there's no more horizontal content to display.It doesn't matter what's actually inside the scroll view.
Swift 5.0