iOS拖动UIImageView

时间:2011-06-27 22:12:02

标签: iphone objective-c uiimageview drag

好的,所以我一直想知道如何实际获取图像视图并拖动它。我正在计划当我拖动图像视图时,当用户将其放置到正确的位置时,它会锁定在那里。我真的不知道如何做到这一点,它已经困扰了我一段时间。

提前非常感谢!

3 个答案:

答案 0 :(得分:7)

如果您不想自己继承视图并处理触摸,也可以使用UIPanGestureRecognizer

在任何类(例如视图控制器)中创建平移识别器并将其添加到视图中:

UIPanGestureRecognizer * panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(handlePanGesture:)];
[myDraggedView addGestureRecognizer:panRecognizer];

然后简单地说:

- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGRect frame = myDraggedView.frame;
    frame.origin = [gestureRecognizer locationInView:myDraggedView.superview];
    myDraggedView.frame = frame;
}

如果您像我一样喜欢Interface Builder,您也可以在图片视图上拖动平移手势识别器,然后将识别器连接到应该声明为handlePanGesture:的{​​{1}} IBAction

答案 1 :(得分:3)

如果您是阅读的人,请查看UIResponder Class Reference,特别是touchesBegantouchesMoved

答案 2 :(得分:0)

我已经使用过这个,但是用户可以自由地拖动imageview并找到他们想要的位置。这是我的swift定制类

class DraggableImageView: UIImageView {
      var beganPoint: CGPoint? = nil
      var originCenter: CGPoint? = nil
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
           if let position = touches.first?.location(in: superview){
                beganPoint = position
                originCenter = center
           }
      }
      override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
      }
      override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
           if let position = touches.first?.location(in: superview){
                let newPosition = CGPoint(x: position.x - (beganPoint?.x)!, y: position.y - (beganPoint?.y)!)
                center = CGPoint(x: (originCenter?.x)! + newPosition.x, y: (originCenter?.y)! + newPosition.y)
           }
      }
}

只需使用您的UIImageView

使用此自定义类