【发布时间】:2017-07-02 09:56:30
【问题描述】:
任何人都可以建议我如何在单击图像视图内的图像时通过鼠标单击或触摸来获取图像的 x 和 y 坐标。
谢谢
【问题讨论】:
-
UITapGestureRecognizer 可能会这样做:stackoverflow.com/questions/16618109/…
任何人都可以建议我如何在单击图像视图内的图像时通过鼠标单击或触摸来获取图像的 x 和 y 坐标。
谢谢
【问题讨论】:
首先,将点击手势监听器添加到您的图像视图中
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)
}
【讨论】:
在图像的子类中这样做非常方便...
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)")
}
您现在可以轻松地将点击的片段传递给视图控制器。
【讨论】: