2

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

Punya
  • 333
  • 2
  • 11
  • UITapGestureRecognizer might do it: https://stackoverflow.com/questions/16618109/how-to-get-uitouch-location-from-uigesturerecognizer – chedabob Jul 02 '17 at 10:13

2 Answers2

5

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)
}
Fangming
  • 23,035
  • 4
  • 95
  • 87
0

Subclass ...

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.

Fattie
  • 35,446
  • 61
  • 386
  • 672