Christie Christie - 1 year ago 75
Swift Question

How to call a method with a parameter on tap of an image?

I understand that the selector method cannot include arguments, but now I'm at a loss as to how I should go about what I want to do.

My objective is to have 5 UI Image Views, each with an image of a star. When the image is tapped, the star should swap images to grey or blue.

My question is, how do I write only one method that handles changing the star image, depending on which star is tapped? Ideally, I would like to send the image as an argument to the method, though I know that is not possible. The only way I can see around this is to write a method for each of the five stars, but as the code would be identical, I feel like there must be a better way.

On View Did Load:

// add tap recognition to rating stars
let tapGestureRecognizerOne = UITapGestureRecognizer(target:self, action:#selector(self.changeStar))
starOneEditImage.userInteractionEnabled = true
let tapGestureRecognizerTwo = UITapGestureRecognizer(target:self, action:#selector(self.changeStar))
starTwoEditImage.userInteractionEnabled = true
let tapGestureRecognizerThree = UITapGestureRecognizer(target:self, action:#selector(self.changeStar))
starThreeEditImage.userInteractionEnabled = true
let tapGestureRecognizerFour = UITapGestureRecognizer(target:self, action:#selector(self.changeStar))
starFourEditImage.userInteractionEnabled = true
let tapGestureRecognizerFive = UITapGestureRecognizer(target:self, action:#selector(self.changeStar))
starFiveEditImage.userInteractionEnabled = true

And then a method to call on tap of the image:

func changeStar() {

print ("star tapped")


Answer Source

I understand that the selector method cannot include arguments

You understand wrong. The parameter to changeStar is the gesture recognizer. And gesture recognizer has a view, and that's the image view you want!

func changeStar(g:UIGestureRecognizer) {
    let v = g.view as! UIImageView
    // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download