在UIScrollView中拖动时,UIView和UIControl之间有所不同

时间:2010-07-19 08:37:48

标签: iphone uiview uiscrollview uicontrol

我有一个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);
    }
}

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

提前致谢!

1 个答案:

答案 0 :(得分:3)

UIScrollView尝试确定用户所考虑的交互类型。如果您点击滚动视图中的视图,该视图将开始触摸。如果用户然后拖动,则滚动视图决定用户想要滚动,因此它将touchesCancelled发送到首先获得该事件的视图。然后它处理拖动本身。

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