Pablo Garcia
Pablo Garcia

Reputation: 381

How do I pass a number to a gesture recognizer action?

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?

Upvotes: 0

Views: 78

Answers (1)

zoul
zoul

Reputation: 104065

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

Upvotes: 2

Related Questions