触摸位置在UIButton行动

时间:2016-10-19 14:07:12

标签: ios swift uibutton ibaction uitouch

我正在尝试获取按钮被点击的位置(x,y)。我找到了答案,但它们不适用于Swift 2.3。 有什么建议? 这就是我的尝试:

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

3 个答案:

答案 0 :(得分:6)

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

斯威夫特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)")
}

要创建带事件的IBAction,请在故事板中的此弹出窗口中选择正确的选项:

enter image description here

答案 1 :(得分:0)

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

}

您可以将手势识别器添加到UIButton,它也可以正常工作

答案 2 :(得分:-1)

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

    }

希望这会有用