UITapGestureRec With Parameters

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 = ; var photoId = event.target.rel;). I explored all options in Objective-C from using the UIGestureRecognizer’s .hash in an NSDictionary to finding out how to implement an NSMapTable in iOS. (Currently NSMapTable is not available in iOS 5).

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