Marc Ibrahim Marc Ibrahim - 1 year ago 145
iOS Question

Location of touch in UIButton action

I'm trying to get the (x,y) location of where a button is tapped. I've found answers but they don't work for Swift 2.3.
Any suggestions?
That's what I have tried:

@IBAction func buttonTapped(sender: AnyObject, forEvent event: UIEvent) {
let buttonView = sender as! UIView;

// get any touch on the buttonView
if let touch = event.touchesForView(buttonView) as? UITouch{
// print the touch location on the button

Answer Source

Swift 2:

@IBAction func buttonPressed(button: UIButton, forEvent event: UIEvent) {
    guard let touch = event.allTouches()?.first else { return }
    let point = touch.locationInView(button)
    print ("point: \(point)")

Swift 3:

@IBAction func buttonPressed(_ button: UIButton, forEvent event: UIEvent) {
    guard let touch = event.allTouches?.first else { return }
    let point = touch.location(in: button)
    print ("point: \(point)")

To create an IBAction with event pick the right option in this popup in your storyboard:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download