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