user7062155 user7062155 - 1 month ago 6
Swift Question

UIImage goes where i tap (But i need it so you can ONLY drag it)

I have a

UIImage
and I linked it into my code and named it "Person"
At the moment where ever I tap on the screen, the
UIImage
jumps to that position, but I want it so the image can ONLY move if I drag it. Here's my code:

var location = CGPointMake(0, 0)

@IBOutlet var Person: UIImageView!

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touch : UITouch = touches.first as UITouch!

location = touch.locationInView(self.view)

Person.center = location

}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touch : UITouch = touches.first as UITouch!

location = touch.locationInView(self.view)

Person.center = location

}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

Person.center = CGPointMake(160, 330)


}

Answer

You can do this with touchesMoved event. But my recommendation is to use UIPanGestureRecognizer.

  1. Declare a UIPanGestureRecognizer object and add it to your image view.
  2. User interaction enable for image view.
  3. Follow this nice apple documented sample code https://developer.apple.com/library/content/samplecode/Touches/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007435