An instance of UIGestureRecognizer
will work only with one view. UIGestureRecognizer
has a single view property -
view
The view the gesture recognizer is attached to. (read-only)
@property(nonatomic, readonly) UIView *view
Discussion You attach (or add) a gesture recognizer to a UIView object using the addGestureRecognizer: method.
So your need to create separate instance of UIGestureRecognizer
(in your case UITapGestureRecognizer
) for each view
and than add them to corresponding view
. Like
UIView *viewA;
UIView *viewB;
UIView *viewC;
...
// views created and customized
...
[viewA setTag:1];
[viewB setTag:2];
[viewC setTag:3];
...
// creating separate gestures and adding them to respective views
UITapGestureRecognizer *viewAGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTouched:)];
[viewA addGestureRecognizer: viewAGestureRecognizer];
UITapGestureRecognizer *viewBGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTouched:)];
[viewB addGestureRecognizer: viewBGestureRecognizer];
UITapGestureRecognizer *viewCGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTouched:)];
[viewC addGestureRecognizer: viewCGestureRecognizer];
- (void) viewTouched:(UITapGestureRecognizer *)tap
{
NSString *s= [NSString stringWithFormat:@"%ld", (long)tap.view.tag];
NSLog(@"%@",s);
}
Now it will print the corresponding view's
tag
(1
for viewA
, 2
for viewB
& 3
for viewC
)
Note :
Also you were doing the reverse rather than adding the gesture
instance on view
you were adding view
on gesture
as
[viewAGestureRecognizer addGestureRecognizer: viewA];
And you need to do it as
[viewA addGestureRecognizer: viewAGestureRecognizer];
and as above in answer.