首页 文章

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

提问于
浏览
0

我有一个 UIButton 实例,我希望获得触摸的确切位置,即使触发连接到它的选择器 .

按钮配置如下:

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.
}

有什么方法可以实现触发 buttonPressed 方法的触摸事件的位置?我对使用 UIGestureRecognizer 实例犹豫不决,因为我实际上有多个具有不同 tag 值的按钮,我用这些按钮在 buttonPressed 方法中执行不同的操作 .

谢谢你的任何建议 .

1 回答

  • 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) {
    
          }
      }
    }
    

    选项2

    添加手势并访问按钮使用

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

    gesture.view

相关问题