【问题标题】:Location of touch in UIButton actionUIButton 动作中的触摸位置
【发布时间】:2017-03-01 05:32:55
【问题描述】:

我正在尝试获取点击按钮的 (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))
    }
}

【问题讨论】:

  • 您已经尝试过的解决方案中的任何代码?

标签: ios swift uibutton ibaction uitouch


【解决方案1】:

斯威夫特 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,请在情节提要的此弹出窗口中选择正确的选项:

【讨论】:

  • @MarcIbrahim 不客气。事实上,您发布的代码也应该可以正常工作。
【解决方案2】:
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,它也可以正常工作

【讨论】:

    【解决方案3】:
    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
            let touch = touches.allObjects[0] as UITouch
            let touchLocation = touch.locationInView(self.view)
    
        }
    

    希望对你有用

    【讨论】:

    • 感谢您的回答,但它不是来自 UIButton 的 IBAction 而不是 touchesBegan 方法。
    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多