2011-11-01 52 views
2

我有三个UILabels。我想检测哪个标签是Tapped,然后检索该标签的字符串值。 这是我如何尝试,我只能设法检测窃听位置,但我无法检测到哪个标签被窃听。如何检测哪个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]; 
} 

回答

4

UIGestureRecognizer有它连接到一个视图的引用,所以你可以从你的标签的标签它:

int touchedtag = recognizer.view.tag; 
documentName = [[pdfs objectAtIndex:touchedtag-1] lastPathComponent]; 
+0

这只是时间的问题;) –

+0

非常感谢,它的作品 – sajaz

4

手势识别器知道它属于哪个视图。

UIView *theView = recognizer.view; 
// cast it to UILabel if you are sure it is one 
UILabel *theLabel = (UILabel *)theView; 
4

当你有标签

// 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 ... 
    } 
+0

谢谢!它帮助我在检测触摸时更改标签文字 – Deeper

3

你为什么要使用标签,按钮上添加GestureRecognizer?只需使用按钮,它们可以配置为看起来就像标签。