点击(swift)时如何获得图像的X和Y坐标

时间:2017-07-02 09:56:31

标签: ios swift xcode

当我点击图像视图内的图像时,任何人体都可以建议如何在鼠标单击或触摸时获得图像的x和y坐标。

由于

2 个答案:

答案 0 :(得分:5)

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

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)
}

答案 1 :(得分:0)

子类...

在图像的子类中执行此操作非常方便...

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)")
    }

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