绑定在其superview中添加到UIPanGestureRecognizer的视图的移动

时间:2010-11-08 16:51:52

标签: iphone uigesturerecognizer

我想知道在使用GestureRecognizer时是否有办法在我的超视图中限制我的UIView的移动。

例如。我有一个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]];
    }
}

感谢代码帮助。

2 个答案:

答案 0 :(得分:0)

您只需要将属性clipsToBounds(将其设置为YES)用于superview。早先有同样的问题。在那之后完美地运作。

答案 1 :(得分:-1)

也许是因为

  

标准UIImageViews,尽管是UIView子类,但不会对添加到它们的手势识别器做出反应

working with uigesturerecognizers