IOS drag and drop UIImageView

Ok, so I always wondered how I can get the image and drag it. I planned when I drag the image, and when the user places it in the right place, it is blocked there. I really have no idea how to do this, and it has ever bothered me.

Thank you very much in advance!

+5
source share
3 answers

If you are reading, check out UIResponderClass Link, and in particular, touchesBeganand touchesMoved.

+3
source

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

Builder , , , handlePanGesture:, IBAction void.

+7

, .

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

0

All Articles