Getting the coordinates from the location I touch the touchscreen

Lukas Köhl picture Lukas Köhl · Nov 9, 2014 · Viewed 43.1k times · Source

I try to get the coordinates from the location where I hit the touchscreen to do put a specific UIImage at this point.

How can I do this?

Answer

Mundi picture Mundi · Nov 9, 2014

In a UIResponder subclass, such as UIView:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject()! as UITouch
    let location = touch.locationInView(self)
}

This will return a CGPoint in view coordinates.

Updated with Swift 3 syntax

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.first!
    let location = touch.location(in: self)
}

Updated with Swift 4 syntax

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self.view)
}