Return tag of the label when it it tapped

2019-06-14 13:52发布

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.

3条回答
贪生不怕死
2楼-- · 2019-06-14 13:57

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.

查看更多
该账号已被封号
3楼-- · 2019-06-14 13:58

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
        }
    }
查看更多
Fickle 薄情
4楼-- · 2019-06-14 14:17

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");
}
查看更多
登录 后发表回答