3

I have a UIButton stretched to the size of the view (covers the view/screen).

I have set a Touchdown action and I need in this action to find out what is the location of the tap/press on the button (get x and y coordinates).

Is it possible?

Roi Mulia
  • 5,626
  • 11
  • 54
  • 105

2 Answers2

3

Create the action function with sender and event params. Then you can get the touch location on the button.

@IBAction func buttonAction(sender: AnyObject, event: UIEvent) {
    // downcast sender as a UIView
    let buttonView = sender as UIView;

    // get any touch on the buttonView
    if let touch = event.touchesForView(buttonView)?.anyObject() as? UITouch {
        // print the touch location on the button
        println(touch.locationInView(buttonView))
    }
}
Ron Fessler
  • 2,701
  • 1
  • 17
  • 22
  • i tried, giving me this followng error : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[beater.ViewController userbeat:]: unrecognized selector sent to instance 0x15853200' – Roi Mulia Nov 18 '14 at 20:00
  • any ideas what is could be? – Roi Mulia Nov 18 '14 at 20:01
  • Something in your code is trying to call a function named `userbeat` in class `beater`. However, the function `userbeat` does not exist or the `beater` object has been dealloc'd. – Ron Fessler Nov 18 '14 at 20:46
  • @IBAction func userbeat(sender: AnyObject , event: UIEvent) { let buttonView = sender as UIView; // get any touch on the buttonView if let touch = event.touchesForView(buttonView)?.anyObject() as? UITouch { // print the touch location on the button println("what is this\(touch.locationInView(buttonView))") } } – Roi Mulia Nov 18 '14 at 21:00
  • oh lol the paste wasnt so well, dont know what is possible that went wrong because they both exist.. – Roi Mulia Nov 18 '14 at 21:01
  • should i create another function or something or another connection from the button mybe? – Roi Mulia Nov 18 '14 at 21:05
  • Yes, on the storyboard, delete the existing connection and reconnect it. The method signature has changed (because we added the event param) but it's still referring to the old method. – Ron Fessler Nov 18 '14 at 21:11
  • reconnect like i am doing as usuall? drag it to the code using split screens? – Roi Mulia Nov 18 '14 at 21:12
  • Works prefectly , you sir just made my day. i wish you good week !! !:) – Roi Mulia Nov 18 '14 at 21:15
0

Swift 3 version of accepted answer:

@IBAction func increaseButtonTapped(sender: UIButton, event: UIEvent) {

    // get any touch on the buttonView

    let events = event.touches(for: sender)

    for event in events! {

        let location = event.location(in: sender)

        print("\(location)")

    }

}
inf1783
  • 944
  • 11
  • 12