EyeQ Tech
EyeQ Tech

Reputation: 7358

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

Upvotes: 0

Views: 60

Answers (2)

Misha
Misha

Reputation: 685

You need to add tag where you're adding imageViews either in storyboard or in code.

then in your imageTapped() method compare them -

func imageTapped(_ sender: UIImageView) {

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

}

Upvotes: 0

Bhavin Ramani
Bhavin Ramani

Reputation: 3219

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

    }
}

Upvotes: 1

Related Questions