Drag and drop images around the screen with quick

I tried this method

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) { let translation = recognizer.translationInView(self.view) if let view = recognizer.view { view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y) } recognizer.setTranslation(CGPointZero, inView: self.view) } 

It works, but the problem is that when I use this method for multiple images, it creates some problems, for example, when dragging one image and changing its position, but when I click and drag the second image. My first image is returning to its original position. Here are the images that I get from the scroll view: When I click on the second image, the first image also goes to its original position

enter image description here

I drag the image, it’s fine here.

enter image description here

+6
source share
2 answers

Auto-layout starts sending images back to where they say they should be.

The easiest way to get around this is to create your images in code instead of creating them in a storyboard.

Sort of:

 let lightBulb = UIImageView(frame: CGRectMake(100, 100, 50, 50)) lightBulb.image = UIImage(named: "lightBulb") lightBulb.contentMode = .ScaleToFill lightBulb.userInteractionEnabled = true lightBulb.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan:")) self.view.addSubview(lightBulb) 
+6
source
 class DraggableImageView: UIImageView { var dragStartPositionRelativeToCenter : CGPoint? override init(image: UIImage!) { super.init(image: image) self.userInteractionEnabled = true //< w00000t!!!1 addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan:")) layer.shadowColor = UIColor.blackColor().CGColor layer.shadowOffset = CGSize(width: 0, height: 3) layer.shadowOpacity = 0.5 layer.shadowRadius = 2 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func handlePan(nizer: UIPanGestureRecognizer!) { if nizer.state == UIGestureRecognizerState.Began { let locationInView = nizer.locationInView(superview) dragStartPositionRelativeToCenter = CGPoint(x: locationInView.x - center.x, y: locationInView.y - center.y) layer.shadowOffset = CGSize(width: 0, height: 20) layer.shadowOpacity = 0.3 layer.shadowRadius = 6 return } if nizer.state == UIGestureRecognizerState.Ended { dragStartPositionRelativeToCenter = nil layer.shadowOffset = CGSize(width: 0, height: 3) layer.shadowOpacity = 0.5 layer.shadowRadius = 2 return } let locationInView = nizer.locationInView(superview) UIView.animateWithDuration(0.1) { self.center = CGPoint(x: locationInView.x - self.dragStartPositionRelativeToCenter!.x, y: locationInView.y - self.dragStartPositionRelativeToCenter!.y) } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ } 
+6
source

All Articles