【问题标题】:iOS (Swift): Location of touch event in UIButton programaticallyiOS(Swift):以编程方式在 UIButton 中触摸事件的位置
【发布时间】:2019-05-10 19:52:56
【问题描述】:

我有一个 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 方法中执行不同的操作。

感谢您的任何建议。

【问题讨论】:

    标签: ios swift uibutton touch


    【解决方案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))
    }
    

    手势视图

    【讨论】:

    • 谢谢。在选项 1 中,触摸按钮时不会调用 touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?)。选项 2 可能是最好的解决方案,谢谢。
    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多