2

I'm new to Swift app development and I would like to know how to add touch events based on where an Image is clicked using Swift. I need to get the coordinates of the area the image is tapped.

Geoffrey
  • 10,843
  • 3
  • 33
  • 46
FallPoet
  • 27
  • 6

2 Answers2

4

You'll need a tap gesture recognizer on the image view, you also need to set the user interaction property to enabled. Then you can get the point from the gesture recognizer's method. Here's some quick code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

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


    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapAction:"))

    self.imageView.userInteractionEnabled = true
    self.imageView.addGestureRecognizer(tapGestureRecognizer)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tapAction(sender: UITapGestureRecognizer) {

    let touchPoint = sender.locationInView(self.imageView) // Change to whatever view you want the point for
}


}
Fred Faust
  • 6,696
  • 4
  • 32
  • 55
0

UPDATE 2017:

Now Selector(String) is deprecated. One can use the new syntax #selector.

Also, the colon at the end is not needed.

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
palamunder
  • 2,555
  • 1
  • 19
  • 20