Difference between UIView and UIControl when dragging inside a UIScrollView

I have a UIScrollView that contains a small subclass of UIView. UIScrollView has scrolling, and I want every UIView to be able to move around inside UIScrollView freely.

My subclass of UIView 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 touchsCancelled: withEvent will be called every time I just drag a UIView a few pixels. But these codes will work correctly if it is a subclass of UIControl. Why?

Thanks in advance!

+3
source share
1 answer

UIScrollView , . , . , , , , , . .

, UIScrollView touchesShouldBegin:withEvent:inContentView: touchesShouldCancelInContentView:.

+3

Source: https://habr.com/ru/post/1755272/


All Articles