2010-11-08 134 views
1

我想知道在使用GestureRecognizer時,是否有方法來限制UIView在其超級視圖中的移動。綁定在UIPanGestureRecognizer中添加的視圖的移動,在其超級視圖中

例如。我有一個UIImageview我加入UIPanGestureRecognizer與動作panPiece。我按照以下方式調整其中心,以避免其移出超級視角。但它不能正常工作。

-(CGPoint) centerWithBounds:(CGPoint)center andViewFrame:(CGRect)viewFrame andBoundingFrame:(CGRect)boundingFrame{ 

CGFloat lowerXBound = boundingFrame.origin.x + (viewFrame.size.width/2); 
CGFloat higherXBound = boundingFrame.origin.x + boundingFrame.size.width - (viewFrame.size.width/2); 

CGFloat lowerYBound = boundingFrame.origin.y + (viewFrame.size.height/2); 
CGFloat higherYBound = boundingFrame.origin.y + boundingFrame.size.height - (viewFrame.size.height/2); 

if (center.x < lowerXBound) { 
    center.x = lowerXBound; 
} 
if (center.x > higherXBound){ 
    center.x = higherXBound; 
} 
if (center.y < lowerYBound) { 
    center.y = lowerYBound; 
} 
if (center.y > higherYBound){ 
    center.y = higherYBound; 
} 

return center; 
} 

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer 
{ 
    UIView *piece = [gestureRecognizer view]; 

    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer]; 

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) { 
     CGPoint translation = [gestureRecognizer translationInView:[piece superview]]; 
     CGPoint translatedCenter = CGPointMake([piece center].x + translation.x, [piece center].y + translation.y); 
    CGPoint center = [self centerWithBounds:translatedCenter andViewFrame:[piece frame] andBoundingFrame:[[piece superview] frame]]; 
     [piece setCenter:center]; 
     [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]]; 
    } 
} 

代碼幫助表示讚賞。

回答

-1

也許是因爲

標準的UIImageViews,儘管是UIView的子類,還沒有反應過來,以增加他們的手勢識別

working with uigesturerecognizers

+0

這是不正確的。你只需要在UIImageView上設置userInteractionEnabled = YES。 – 2011-11-10 17:16:23

0

你只需要使用屬性clipsToBounds (將其設置爲YES)添加到超級視圖。早些時候有同樣的問題。在那之後完美地工作。

相關問題