触摸在 UIButton 动作中的位置
Location of touch in UIButton action
我正在尝试获取点击按钮的 (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))
}
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.allObjects[0] as UITouch
let touchLocation = touch.locationInView(self.view)
}
希望这会有用
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)")
}
要创建一个带有事件的 IBAction,请在故事板的这个弹出窗口中选择正确的选项:
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,它也会正常工作
我正在尝试获取点击按钮的 (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))
}
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.allObjects[0] as UITouch
let touchLocation = touch.locationInView(self.view)
}
希望这会有用
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)")
}
要创建一个带有事件的 IBAction,请在故事板的这个弹出窗口中选择正确的选项:
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,它也会正常工作