iOS( swift ): Location of touch event in UIButton programatically

标签 ios swift uibutton touch

我有一个 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

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

手势. View

关于iOS( swift ): Location of touch event in UIButton programatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696778/

相关文章:

ios - 使用模拟器显示保存的路径,但在使用实际智能 watch 设备(录音机)进行测试时不显示

iphone - UINavigationBar 标题标签文字

ios - 多层 scn 文件需要时间来渲染 arkit

iphone - 表格 View 中的事件指示器

ios - 获取不可见的 CollectionView 单元格

ios - 快速获取 UIButton 按下的位置

ios - Swift viewForAnnotation pin zposition 不在顶部

swift - 对 swift 中弱委托(delegate)的困惑

iphone - 如何在 ios 中的 UIButtons 上创建线条?

ios - 按下时禁用按钮 30 秒,再次启用,然后再次按下时禁用