A small blog post for those attempting to create multiple UITapGestureRecognizers handled by one function. Coming from JavaScript, it’s easy to “attach” arbitrary data to elements or objects and references them on the event handler. (el.rel =
Finally, I RTFM’d the UIView base object documentation and found exactly what I was looking for; .tag. Although limited to NSInteger, more than enough to identify which view the taps were coming from.
For example, if your project programmatically creates multiple UIImageViews and you want one function to handle all incoming taps, the code is as simple as.
int i;
for(i = 0; i < count; i++) {
// some image
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// attach to some view
imageView.tag = i;
UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]
initWithTarget: self
action: @selector(imageTap:)];
[imageView addGestureRecognizer:g];
}
// handler
- (void)imageTap:(UITapGestureRecognizer *)sender {
// identifier can be referenced in sender.view.tag
}
