Detecting taps in any UIView subclass

This one is a quick and easy trick. How do you detect taps in any UIView?.
Simple. You need to use the UITapGestureRecognizer class… this way:

[cc lang=”objc”]
// Alloc the gesture recognizer
UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
[tapGestureRecognizer setNumberOfTapsRequired:1];
[anyRandomView addGestureRecognizer:tapGestureRecognizer];
[anyRandomView setUserInteractionEnabled:YES];

[tapGestureRecognizer release];
tapGestureRecognizer = nil;

%d bloggers like this: