IOS Gesture Handling: where to add a gesture recognizer when using a custom UIView

ios5uigesturerecognizer

I have a view controller where I display a grid/array of images, where every image view is a custom nib (custom nib because images have a name & like/dislike icon too). So I displayed the grid of images doing something like this in my view controller viewDidLoad.

int row=0, col=0;
for (int i=0; i<arrayImg.count; i++) {
    NSArray *topObj = [[NSBundle mainBundle] loadNibNamed:@"CustomImageView" owner:nil options:nil];
    CustomImageView *imgView = [topObj objectAtIndex:0];
    imgView.frame = CGRectMake(180*col+10, 180*row+10, 170, 170);

    // custom image values inserted here

    [self.view addSubView:imgView];

    // update the row,col variables here
}

Now I need to add a tap gesture recognizer to every image displayed on the screen. It seems logical to me to add the gesture recognizer inside the custom nib/class, CustomImageView in this case. CustomImageView extends UIView, so it seems a gesture recognizer cannot be declared here (auto-complete does not appear, syntax highlighting does not work either). What am I missing over here?

Best Answer

You can surely add a gesture recognizer to your CustomImageView (provided it is a UIView). Try something like this:

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[tapRecognizer setNumberOfTapsRequired:1];
[tapRecognizer setDelegate:self];

[imgView addGestureRecognizer:tapRecognizer];

Note that the only method that you should see auto-completed is addGestureRecognizer.

In general, prefer the official documentation (or the compiler, if you like) over auto-completion in order to decide whether a feature is present or not. Auto-completion is not always right, in my experience.

Related Topic