You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何获取点击UIImageView时的触摸位置?

获取UIImageView点击位置的Swift实现方法

嘿,这事儿其实挺简单的,我给你两种常用的实现方式,按需选就行:

方法一:使用UITapGestureRecognizer(推荐)

UIImageView默认是关闭用户交互的,所以第一步得先打开它,然后给它加个点击手势就能拿到坐标了:

  1. 开启用户交互
    在初始化或者viewDidLoad里先把这个属性设为true:

    yourImageView.isUserInteractionEnabled = true
    
  2. 添加点击手势并实现回调
    还是在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方法:

  1. 创建自定义子类

    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)")
            // 这里还可以通过代理或者闭包把坐标传递给控制器
        }
    }
    
  2. 使用这个子类
    不管是代码创建还是Storyboard里拖的,把UIImageView的类改成TapableImageView,记得同样要开启用户交互:

    let customImageView = TapableImageView()
    customImageView.isUserInteractionEnabled = true
    

小提醒:如果需要的是相对于图片内容的坐标(而不是ImageView的frame),那还得考虑图片的contentMode,比如当图片是缩放填充的时候,需要做额外的坐标转换哦!

内容的提问来源于stack exchange,提问作者Aamir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:50:17