【问题标题】:Bound the movement of a view which is added to UIPanGestureRecognizer, within its superview在其父视图中绑定添加到 UIPanGestureRecognizer 的视图的移动
【发布时间】:2011-05-06 18:37:54
【问题描述】:

我想知道是否有办法在使用 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]];
    }
}

感谢代码帮助。

【问题讨论】:

    标签: iphone uigesturerecognizer


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      也许是因为

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

      working with uigesturerecognizers

      【讨论】:

      • 这不是真的。你只需要在 UIImageView 上设置 userInteractionEnabled = YES。
      猜你喜欢
      • 2013-11-26
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多