1

我想知道是否有一种方法可以在使用 GestureRecognizer 时将我的 UIView 的移动限制在其超级视图中。

例如。我有一个 UIImageview,我向其添加了带有动作 panPiece 的 UIPanGestureRecognizer。我通过以下方式调整它的中心,以避免它移动到它的超级视图之外。但它不能正常工作。

-(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]];
    }
}

代码帮助表示赞赏。

4

2 回答 2

1

您只需要使用属性 clipsToBounds(将其设置为 YES)到超级视图。之前有同样的问题。之后完美运行。

于 2011-09-27T13:06:27.387 回答
-1

也许是因为

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

使用uigesturerecognizers

于 2011-03-04T06:30:29.890 回答