我有三个UILabels。我想检测哪个标签是Tapped,然后检索该标签的字符串值。 这就是我的尝试,我只能设法检测轻敲的位置,但我无法检测到哪个标签被点击。
标签制作
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];
}
答案 0 :(得分:4)
UIGestureRecognizer引用了它所附加的视图,因此您可以从中获取标签的标签:
int touchedtag = recognizer.view.tag;
documentName = [[pdfs objectAtIndex:touchedtag-1] lastPathComponent];
答案 1 :(得分:4)
手势识别器知道它属于哪个视图。
UIView *theView = recognizer.view;
// cast it to UILabel if you are sure it is one
UILabel *theLabel = (UILabel *)theView;
答案 2 :(得分:4)
在标签上添加GestureRecognizer
// called when touch is began or when user touches
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
UILabel *theLabel = (UILabel *)touch.view;
if (theLabel.tag == 1)
{}
else if ...
}
答案 3 :(得分:3)
为什么要将标签用作按钮?只需使用按钮,就可以将它们配置为看起来就像标签一样。