I have 5 labels in my view, respectively tagged 1, 2, 3, 4 and 5. I have enabled user interaction on them, and added a tap gesture.
Now what I want is to get the tag of the label being touched.
I am doing something like this:
tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureSelector)];
tapGesture.numberOfTapsRequired = 1.0;
- (void)tapGestureSelector :(id)sender
{
// I need the tag to perform different tasks.
// So that I would like to get the touched label's tag here.
}
If I am not clear in my question please ask me.
Thanks in anticipation for helping.
Firstly I've added oneLabel
and twoLabel
as subview to self.view
. Then I think there is no need to get the tag.
CGPoint tapPoint = [tapGesture locationInView:self.view];
if (CGRectContainsPoint(self.oneLabel.frame, tapPoint)) {
NSLog(@"tapped one label");
} else if (CGRectContainsPoint(self.twoLabel.frame, tapPoint)) {
NSLog(@"tapped two label");
}
For accessing the tag of UILabel
you need to use the following code in your tapGestureSelector
method.
- (void)tapGestureSelector :(id)sender
{
UITapGestureRecognizer *gesture = (UITapGestureRecognizer *)sender;
int labelTag = gesture.view.tag;
NSlog(@"Clicked label %d", labelTag);
switch(labelTag)
{
case 1:
NSlog(@"Clicked on label 1");
break;
case 2:
NSlog(@"Clicked on label 2");
break;
//so on
}
}
I find the solution in this way and it worked for me very fine. I hope that it will also help you. It is very simple and short.
We can get the Tag of the label by adding this function into our .m file.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
UILabel *label=(UILabel *)touch.view;
NSLog(@"Label that is tapped has tag %d",label.tag);
}
Thanks again for all of your very nice suggestions and answers. I hope I will always get good answers of my all questions from SO in future. Thanks to all again.