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.
Asked
Active
Viewed 2,309 times
2
-
Hey.Could you share some code please? – Korpel Oct 30 '15 at 00:42
2 Answers
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
-
I think this code will also show tap location even when outside of the `UIImage`. Other than that is legit! – Korpel Oct 30 '15 at 00:51
-
1@Korpel I'm not sure what you mean, the gesture recognizer is attached to the imageView. – Fred Faust Oct 30 '15 at 00:52
-
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