Getting the coordinates from the location I touch the touchscreen

This is work in Swift 2.0

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let position :CGPoint = touch.locationInView(view)
        print(position.x)
        print(position.y)

    }
}

Taking this forward for Swift 3 - I'm using:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: self)
        print(position.x)
        print(position.y)
    }
}

Happy to hear any clearer or more elegant ways to produce the same result


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)
}