Taxi Noi Bai Ha Noi Taxi Noi Bai Ha Noi - 1 month ago 12
iOS Question

Recognize which View calls the Tap function

I know how to add tappability to the

UIImageView
, however, there are 2 image views and I want to distinguish them to call the correct function. However, I can't seem to get the correct
sender
.

func addTappability (view imageView:UIImageView){
//add tapping function for image

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

func imageTapped(_ sender: UIImageView) {

//Problem here, can't get correct sender
if ( sender == photoImageViewLeft) {
//do one thing
}else {
//do the other
}
}

Answer

Replace your function with this:

func imageTapped(_ sender: UITapGestureRecognizer) {

    if let imageView = sender.view as? UIImageView {
        if ( imageView == photoImageViewLeft ) {
            print("Image1 Tapped")
        }else {
            print("Image2 Tapped")
        }

    }
}
Comments