3

我有一个 UIScrollView ,其中包含一些小的 UIView 子类。UIScrollView 启用了滚动,我希望每个 UIView 都可以在 UIScrollView 内自由拖动。

我的 UIView 子类有这个方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] != self) {
        return;
    }
    CGPoint touchPoint = [touch locationInView:self.superview];
    originalX = self.center.x;
    originalY = self.center.y;
    offsetX = originalX - touchPoint.x;
    offsetY = originalY - touchPoint.y;
    [self.superview bringSubviewToFront:self];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == self) {
        CGPoint location = [touch locationInView:self.superview];
        CGFloat x = location.x + offsetX;
        CGFloat y = location.y + offsetY;
        self.center = CGPointMake(x, y);        
        return;
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == self) {
        self.center = CGPointMake(originalX, originalY);
    }
}

我发现每次只拖动 UIView 几个像素时都会调用 touchesCancelled:withEvent 。但是如果它是 UIControl 的子类,这些代码将正常工作。为什么?

提前致谢!

4

1 回答 1

3

UIScrollView 试图确定用户心中的交互类型。如果您在滚动视图中点击一个视图,该视图就会开始触摸。如果用户随后拖动,则滚动视图决定用户想要滚动,因此它将 touchesCancelled 发送到首先获得事件的视图。然后它自己处理拖动。

要启用您自己的子视图拖动,您可以继承 UIScrollView 并覆盖touchesShouldBegin:withEvent:inContentView:touchesShouldCancelInContentView:

于 2010-07-19T08:56:24.757 回答