0

I have the next code

var i = 0
for answer in answeres{ 
    let singleTap = UITapGestureRecognizer(target: self, action:#selector(tapDetected(_:))
    imageView.addGestureRecognizer(singleTap)
    i+=1
}

func tapDetected(position : Int) {
    print(position)
}

How can I pass the var 'i' to each imageView, so when the user click the imageView, it prints the correct number in the log?

zoul
  • 102,279
  • 44
  • 260
  • 354
Pablo Garcia
  • 361
  • 6
  • 23
  • Possible duplicate of [Passing parameters on button action:@selector](http://stackoverflow.com/questions/3716633/passing-parameters-on-button-actionselector) – Laffen Apr 28 '16 at 11:39

1 Answers1

2

The method called by the recognizer is passed the recognizer as a first argument:

func tapDetected(sender: UITapGestureRecognizer) {}

Which means you can use the view property of the recognizer to access the view associated with it. And the number can be stored as the view tag:

var i = 0
for answer in answers {
   let singleTap = …
   let imageView = …
   imageView.addGestureRecognizer(singleTap)
   imageView.tag = i
   i = i + 1
}

func tapDetected(sender: UITapGestureRecognizer) {
    print(sender.view.tag)
}
zoul
  • 102,279
  • 44
  • 260
  • 354
  • Perfect! I was looking this! but if I want to pass a object to the func? – Pablo Garcia Apr 28 '16 at 11:44
  • Can’t the function get the object somewhere using the view tag? – zoul Apr 28 '16 at 11:46
  • Yes it can. Thank you so much – Pablo Garcia Apr 28 '16 at 11:48
  • ugh.... `for (index, answer) in answers.enumerate() {` .... `imageView.tag = index`... but even that is kind of weak sauce. It'd be better if we just had a `class AnswerView: UIImageView` which had a property `var answerCount: Int?` and set that. Using the tag is dangerous. People abuse it all of the time, and even if they don't, it's kind of magic and doesn't really tell you what it represents. – nhgrif Apr 28 '16 at 11:59
  • If you can keep the problem encapsulated in a simple single class, I don’t think there’s any real harm in using the tag. – zoul Apr 28 '16 at 13:03