简体   繁体   中英

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
        print(touch.locationInView(buttonView))
    }
}

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:

在此处输入图片说明

func addGesture() {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.buttonTapped(sender:)));
gestureRecognizer.numberOfTapsRequired = 1;
gestureRecognizer.numberOfTouchesRequired = 1;
button.addGestureRecognizer(gestureRecognizer)  }


func buttonTapped(sender:UIGestureRecognizer) {
    print(sender.location(in: button))

}

You can add Gesture recognizer to UIButton and it will work as well

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
        let touch = touches.allObjects[0] as UITouch
        let touchLocation = touch.locationInView(self.view)

    }

Hope this will be useful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM