Swift中如何获取点击UIImageView时的触摸位置?
获取UIImageView点击位置的Swift实现方法
嘿,这事儿其实挺简单的,我给你两种常用的实现方式,按需选就行:
方法一:使用UITapGestureRecognizer(推荐)
UIImageView默认是关闭用户交互的,所以第一步得先打开它,然后给它加个点击手势就能拿到坐标了:
开启用户交互
在初始化或者viewDidLoad里先把这个属性设为true:yourImageView.isUserInteractionEnabled = true添加点击手势并实现回调
还是在viewDidLoad里,创建手势并绑定处理方法:let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleImageViewTap(_:))) yourImageView.addGestureRecognizer(tapGesture)然后实现对应的处理方法,在这里获取触摸坐标:
@objc func handleImageViewTap(_ gesture: UITapGestureRecognizer) { guard let imageView = gesture.view as? UIImageView else { return } // 获取相对于imageView的触摸坐标 let touchPoint = gesture.location(in: imageView) print("点击位置:x = \(touchPoint.x), y = \(touchPoint.y)") }
方法二:自定义UIImageView子类,重写触摸方法
如果你的UIImageView有自定义逻辑,也可以直接子类化它,重写touchesBegan方法:
创建自定义子类
class TapableImageView: UIImageView { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with event: event) guard let touch = touches.first else { return } // 获取相对于当前ImageView的坐标 let touchPoint = touch.location(in: self) print("点击位置:x = \(touchPoint.x), y = \(touchPoint.y)") // 这里还可以通过代理或者闭包把坐标传递给控制器 } }使用这个子类
不管是代码创建还是Storyboard里拖的,把UIImageView的类改成TapableImageView,记得同样要开启用户交互:let customImageView = TapableImageView() customImageView.isUserInteractionEnabled = true
小提醒:如果需要的是相对于图片内容的坐标(而不是ImageView的frame),那还得考虑图片的contentMode,比如当图片是缩放填充的时候,需要做额外的坐标转换哦!
内容的提问来源于stack exchange,提问作者Aamir
相关产品推荐
相关产品推荐

