简体   繁体   English

iOS(Swift):以编程方式在UIButton中触摸事件的位置

[英]iOS (Swift): Location of touch event in UIButton programatically

I have a UIButton instance that I want to get the exact location of the touch even that triggers the selector attached to it. 我有一个UIButton实例,我希望获得触摸的确切位置,甚至触发与其连接的选择器。

The button is configured as follows: 该按钮的配置如下:

private var button: UIButton!

private func setupButton() {
    button = UIButton(frame: frame)
    button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}

@objc private func buttonPressed(_ button: BounceButton) {
    // I need the location of the touch event that triggered this method.
}

What is the method for achieving the location of the touch event that triggered the buttonPressed method, please? 请问用于实现触发buttonPressed方法的触摸事件的位置的方法是什么? I'm hesitant to use a UIGestureRecognizer instance as I actually have multiple buttons with different tag values that I use to do different things within the buttonPressed method. 我很犹豫使用UIGestureRecognizer实例,因为我实际上有多个具有不同tag值的按钮,这些按钮用于在buttonPressed方法中执行不同的操作。

Thanks for any suggestions. 感谢您的任何建议。

Option 1 选项1

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  if let touch = touches.first {
     let position = touch.location(in: view)
      if button.frame.contains(position) {

      }
  }
}

Option2 选项2

add gesture and to access the button use 添加手势并访问按钮使用

@objc func tapped(_ gesture:UITapGestureRecognizer)
{
    print(gesture.view?.tag)
    print(gesture.location(in: gesture.view))
}

gesture.view gesture.view

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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