2015-01-06 43 views
0

我尝试在UIView中实现一些UIImageView的拖放操作。它目前正在运行,只是您可以将图像视图从父视图拖出屏幕。我知道我必须检查一下,看看这些意见是否超出了父母的范围......但我正努力实现它!有人对这个有经验么?对于Windows Phone客户端,只需要以下行;iOS在父界内拖放

 var dragBehavior = new MouseDragElementBehavior {ConstrainToParentBounds = true}; 

我现在的手势代码是在这里;

private UIPanGestureRecognizer CreateGesture(UIImageView imageView) 
    { 
     float dx = 0; 
     float dy = 0; 

     var panGesture = new UIPanGestureRecognizer((pg) => 
     { 
      if ((pg.State == UIGestureRecognizerState.Began || pg.State == UIGestureRecognizerState.Changed) && (pg.NumberOfTouches == 1)) 
      { 
       var p0 = pg.LocationInView(View); 
       if (dx == 0) 
        dx = (float)p0.X - (float)imageView.Center.X; 
       if (dy == 0) 
        dy = (float)p0.Y - (float)imageView.Center.Y; 

       float newX = (float)p0.X - dx; 
       float newY = (float)p0.Y - dy; 
       var p1 = new PointF(newX, newY); 
       imageView.Center = p1; 
      } 
      else if (pg.State == UIGestureRecognizerState.Ended) 
      { 
       dx = 0; 
       dy = 0; 
      } 
     }); 
     return panGesture; 
    } 

回答

0

我用下面的代码解决了这个问题;

 var panGesture = new UIPanGestureRecognizer((pg) => 
     { 
      if ((pg.State == UIGestureRecognizerState.Began || pg.State == UIGestureRecognizerState.Changed) && (pg.NumberOfTouches == 1)) 
      { 
       var p0 = pg.LocationInView(View); 
       if (dx == 0) 
        dx = (float)p0.X - (float)imageView.Center.X; 
       if (dy == 0) 
        dy = (float)p0.Y - (float)imageView.Center.Y; 

       float newX = (float)p0.X - dx; 
       float newY = (float)p0.Y - dy; 
       var p1 = new PointF(newX, newY); 


       // If too far right... 
       if (p1.X > imageView.Superview.Bounds.Size.Width - (imageView.Bounds.Size.Width/2)) 
        p1.X = (float) imageView.Superview.Bounds.Size.Width - (float)imageView.Bounds.Size.Width/2; 
       else if (p1.X < 0 + (imageView.Bounds.Size.Width/2)) // If too far left... 
        p1.X = 0 + (float)(imageView.Bounds.Size.Width/2); 

       // If too far down... 
       if (p1.Y > imageView.Superview.Bounds.Size.Height - (imageView.Bounds.Size.Height/2)) 
        p1.Y = (float)imageView.Superview.Bounds.Size.Height - (float)imageView.Bounds.Size.Height/2; 
       else if (p1.Y < 0 + (imageView.Bounds.Size.Height/2)) // If too far up... 
        p1.Y = 0 + (float)(imageView.Bounds.Size.Height/2); 

       imageView.Center = p1; 
      } 
      else if (pg.State == UIGestureRecognizerState.Ended) 
      { 
       // reset offsets when dragging ends so that they will be recalculated for next touch and drag that occurs 
       dx = 0; 
       dy = 0; 
      } 
     });