开发者

Different between UIView and UIControl when drag inside UIScrollView

开发者 https://www.devze.com 2023-01-07 16:32 出处:网络
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.

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 = ori开发者_运维知识库ginalY - 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!


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:.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号