2011-11-01 1 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

제스처 인식기는 자신이 어떤보기에 속해 있는지 알고 있습니다. 당신이

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

? 대신 버튼을 사용하면 레이블처럼 보이도록 구성 할 수 있습니다.

+0

고마워요! 터치 감지하면서 라벨 텍스트를 바꿀 수있었습니다. – Deeper

3

왜 당신이 버튼으로 레이블을 사용 하시겠습니까 라벨에 GestureRecognizer를 추가함에 따라

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