我的视图中有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.
}
如果我不清楚我的问题,请问我。
感谢您的期待。
答案 0 :(得分:1)
要访问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
}
}
答案 1 :(得分:1)
首先,我已将oneLabel
和twoLabel
作为子视图添加到self.view
。然后我认为没有必要得到标签。
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");
}
答案 2 :(得分:1)
我以这种方式找到解决方案,对我来说非常好。我希望它也会对你有所帮助。它非常简单而且简短。
我们可以通过将此函数添加到.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);
}
再次感谢您提供的所有非常好的建议和答案。我希望将来我总能得到很好的答案。再次感谢所有人。