2010-07-19 35 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