can any body suggest how can I get x and y coordinate of image in a mouse click or touch when I click in image that is inside image view.
Thanks
can any body suggest how can I get x and y coordinate of image in a mouse click or touch when I click in image that is inside image view.
Thanks
First, add on click gesture listener to your image view
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
Then in your handler, find the location of the tap in your image view in this way
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let cgpoint = tapGestureRecognizer.location(in: imageView)
print(cgpoint)
}
It's very handy to do this in a subclass of an image...
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)
}
}
In particular, imagine some sort of image which has on it (say) five parts to click on from left to right.
@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)")
}
You can now easily pass on the segment-clicked to the view controller.