views:

187

answers:

1

Hi there,

I have a UIScrollView which contains some small UIView subclass. UIScrollView is scroll enabled, and I want each UIView can be dragged inside UIScrollView freely.

My UIView subclass has this method:

- (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);
    }
}

I found touchesCancelled:withEvent will be called each time I just drag UIView several pixels. But these codes will work correctly if it is subclass of UIControl. Why?

Thanks in advance!

+1  A: 

UIScrollView tries to determine what kind of interaction the user has in mind. If you tap a view inside a scroll view, that view gets the touch began. If the user then drags, the scroll view decides that the user wants to scroll, so it sends touchesCancelled to the view which first got the event. It then handles the dragging itself.

To enable your own dragging of subviews, you can subclass UIScrollView and override touchesShouldBegin:withEvent:inContentView: and touchesShouldCancelInContentView:.

Nikolai Ruhe
thx. But why UIControl can be drag correctly? UIScrollView treats it different?
gwang
I read the document of touchesShouldCancelInContentView:, UIControl is treated different.Thanks again.
gwang