如何检测哪个 UILabel 被点击?
我有三个 UILabel。我想检测哪个标签被点击,然后检索该标签的字符串值。 这就是我正在尝试的方式,我只能设法检测被点击的位置,但我无法检测被点击的标签。
标签创建
for (NSInteger i=1; i<=[pdfs count]; i++){
UILabel *newLabel=[[UILabel alloc] init];
newLabel.text = [NSString stringWithFormat:[[pdfs objectAtIndex:(i-1)] lastPathComponent]];
newLabel.frame = CGRectMake(10, 60*i, 320, 20);
newLabel.tag=i;
newLabel.font = [UIFont systemFontOfSize:20.0f];
newLabel.backgroundColor = [UIColor clearColor];
newLabel.userInteractionEnabled = YES;
[self.view addSubview:newLabel];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[newLabel addGestureRecognizer:singleTap];
[newLabel release], newLabel=nil;
[singleTap release];
}
检测点击
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
CGPoint location;
location = [recognizer locationInView:self.view];
NSString *documentName;
if(location.y<150.0){
documentName = [[pdfs objectAtIndex:0] lastPathComponent];
}
else{
documentName = [[pdfs objectAtIndex:1] lastPathComponent];
}
I have three UILabels. I want to detect which label is Tapped, and then retrieve the string value of that label.
this is how I am trying, I could only manage to detect tapped position, But I couldn't detect which label was tapped.
Label Creation
for (NSInteger i=1; i<=[pdfs count]; i++){
UILabel *newLabel=[[UILabel alloc] init];
newLabel.text = [NSString stringWithFormat:[[pdfs objectAtIndex:(i-1)] lastPathComponent]];
newLabel.frame = CGRectMake(10, 60*i, 320, 20);
newLabel.tag=i;
newLabel.font = [UIFont systemFontOfSize:20.0f];
newLabel.backgroundColor = [UIColor clearColor];
newLabel.userInteractionEnabled = YES;
[self.view addSubview:newLabel];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[newLabel addGestureRecognizer:singleTap];
[newLabel release], newLabel=nil;
[singleTap release];
}
Detect Taps
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
CGPoint location;
location = [recognizer locationInView:self.view];
NSString *documentName;
if(location.y<150.0){
documentName = [[pdfs objectAtIndex:0] lastPathComponent];
}
else{
documentName = [[pdfs objectAtIndex:1] lastPathComponent];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
手势识别器知道它属于哪个视图。
A gesture recognizer knows what view it belongs to.
为什么要使用标签作为按钮?只需使用按钮即可,它们可以配置为看起来像标签一样。
Why do you want to use labels as buttons? Just use buttons instead, they can be configured to look just like labels.
正如您在标签上添加
GestureRecognizer
As you have add
GestureRecognizer
on labelUIGestureRecognizer 有一个对其所附加视图的引用,因此您可以从中获取标签的标签:
UIGestureRecognizer has a reference to a view it is attached to, so you can get your label's tag from it: