【问题标题】:How to get X and Y co-ordinate of image when i click ( swift)单击时如何获取图像的 X 和 Y 坐标(快速)
【发布时间】:2017-07-02 09:56:30
【问题描述】:

任何人都可以建议我如何在单击图像视图内的图像时通过鼠标单击或触摸来获取图像的 x 和 y 坐标。

谢谢

【问题讨论】:

标签: ios swift xcode


【解决方案1】:

首先,将点击手势监听器添加到您的图像视图中

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)

然后在你的处理程序中,以这种方式在你的图像视图中找到点击的位置

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let cgpoint = tapGestureRecognizer.location(in: imageView)

    print(cgpoint)
}

【讨论】:

    【解决方案2】:

    子类 ...

    在图像的子类中这样做非常方便...

    class SegmentyImage: UIIImageView {
    
        override func common() {
            super.common()
            isUserInteractionEnabled = true
            backgroundColor = .clear
            addGestureRecognizer(
              UITapGestureRecognizer(target: self, action: #selector(clicked)))
        }
        
        @objc func clicked(g: UITapGestureRecognizer) {
            let p = g.location(in: self)
            print(p.x)
        }
    }
    

    特别是,想象一下某种图像,上面有(比如说)五个可供从左到右点击的部分。

        @objc func clicked(g: UITapGestureRecognizer) {
            let p = g.location(in: self)
            if self.frame.size.width <= 0 { return; }
            let segmentIndex: Int = Int( (p.x / self.frame.size.width) * 5.0 )
            print("section is .. \(segmentIndex)")
        }
    

    您现在可以轻松地将点击的片段传递给视图控制器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2015-04-04
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多