2010-07-19 73 views
3

我有一个包含一些小UIView子类的UIScrollView。 UIScrollView启用滚动,我希望每个UIView都可以在UIScrollView内自由拖动。UIView和UIControl在UIScrollView中拖动时不同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:withEvent将每次我只需将UIView的几个像素调用。但是如果它是UIControl的子类,这些代码将正常工作。 为什么?

在此先感谢!

回答

3

UIScrollView试图确定用户想要什么样的交互。如果您在滚动视图中点击视图,该视图就会开始触摸。如果用户拖动,则滚动视图决定用户想要滚动,因此它将触发取消发送到首先获取该事件的视图。然后它处理拖动本身。

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

+0

thx。但为什么UIControl可以正确拖拽? UIScrollView对待它不同? – gwang 2010-07-19 09:07:49

+0

我读了touchesShouldCancelInContentView的文件,UIControl被区别对待。 再次感谢。 – gwang 2010-07-19 09:15:05