当标签被点击时返回标签

我在我的视图中有5个标签,分别标记为1,2,3,4和5.我已经启用了用户交互 ,并添加了一个轻击手势。

现在我想要的是标签被触摸的标签。

我正在做这样的事情:

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. } 

如果我不清楚我的问题,请问我。

感谢您期待的帮助。

首先,我添加了一个oneLabeltwoLabel作为子视图twoLabel 。 那么我认为没有必要得到标签。

 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"); } 

要访问UILabel的标签,您需要在tapGestureSelector方法中使用以下代码。

 - (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 } } 

我以这种方式find解决scheme,对我来说非常好。 我希望它也能帮助你。 这是非常简单和短。

我们可以通过将这个函数添加到我们的.m文件中来获得标签的标签。

 -(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); } 

再次感谢您所有非常好的build议和答案。 我希望将来我会一直很好的回答我所有的问题。 再次感谢所有。