问题描述
我有一个 UIScrollView
只允许水平滚动,我想知道用户滚动的方向(左,右).我所做的是将 UIScrollView
子类化并覆盖 touchesMoved
方法:
I have a UIScrollView
with only horizontal scrolling allowed, and I would like to know which direction (left, right) the user scrolls. What I did was to subclass the UIScrollView
and override the touchesMoved
method:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
float now = [touch locationInView:self].x;
float before = [touch previousLocationInView:self].x;
NSLog(@"%f %f", before, now);
if (now > before){
right = NO;
NSLog(@"LEFT");
}
else{
right = YES;
NSLog(@"RIGHT");
}
}
但是当我移动时,有时根本不会调用此方法.你怎么看?
But this method sometimes doesn't get called at all when I move. What do you think?
推荐答案
确定方向相当简单,但请记住,在一个手势的过程中,方向可能会改变多次.例如,如果您有一个滚动视图并打开了分页,并且用户滑动以转到下一页,则初始方向可能是向右,但是如果您打开了弹跳,它将暂时没有方向并且然后短暂地向左走.
Determining the direction is fairly straightforward, but keep in mind that the direction can change several times over the course of a gesture. For example, if you have a scroll view with paging turned on and the user swipes to go to the next page, the initial direction could be rightward, but if you have bounce turned on, it will briefly be going in no direction at all and then briefly be going leftward.
要确定方向,您需要使用 UIScrollView scrollViewDidScroll
委托.在此示例中,我创建了一个名为 lastContentOffset
的变量,我用它来比较当前内容偏移量与前一个内容偏移量.如果它更大,则 scrollView 向右滚动.如果小于则 scrollView 向左滚动:
To determine the direction, you'll need to use the UIScrollView scrollViewDidScroll
delegate. In this sample, I created a variable named lastContentOffset
which I use to compare the current content offset with the previous one. If it's greater, then the scrollView is scrolling right. If it's less then the scrollView is scrolling left:
// somewhere in the private class extension
@property (nonatomic, assign) CGFloat lastContentOffset;
// somewhere in the class implementation
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
ScrollDirection scrollDirection;
if (self.lastContentOffset > scrollView.contentOffset.x) {
scrollDirection = ScrollDirectionRight;
} else if (self.lastContentOffset < scrollView.contentOffset.x) {
scrollDirection = ScrollDirectionLeft;
}
self.lastContentOffset = scrollView.contentOffset.x;
// do whatever you need to with scrollDirection here.
}
我使用以下枚举来定义方向.将第一个值设置为 ScrollDirectionNone 的额外好处是在初始化变量时将该方向设为默认值:
I'm using the following enum to define direction. Setting the first value to ScrollDirectionNone has the added benefit of making that direction the default when initializing variables:
typedef NS_ENUM(NSInteger, ScrollDirection) {
ScrollDirectionNone,
ScrollDirectionRight,
ScrollDirectionLeft,
ScrollDirectionUp,
ScrollDirectionDown,
ScrollDirectionCrazy,
};
这篇关于在 UIScrollView 中查找滚动方向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!