Umair Afzal Umair Afzal - 6 months ago 53
Swift Question

dragging images around the screen using swift

i have 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 is working but the problem is that when i use this method on multiple images it create some issues for example
when drag one image and change its position but when i click and drag second image . my first image come back to original position
i am getting images from a scroll view
and when i click second image 1st image also go the original position

i am dragging an image its fine here

please help

Answer

Auto Layout is running a putting your images back to where the constraints say they should be.

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

Something like:

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)