Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a UILabel was touched?

I am trying to determine if a UILabel was touched and if so do something. Give ..

.
.
.
UILabel * site = [[UILabel alloc] initWithFrame:CGRectMake(0, 185, 320, 30)];
site.text = [retriever.plistDict valueForKey:@"url"];
site.textAlignment =UITextAlignmentCenter;
site.backgroundColor = [UIColor clearColor];
site.textColor = [UIColor whiteColor];
site.userInteractionEnabled = YES;
[theBgView addSubview:site];
[site release];
.
.
.    

Then I write the callback.

 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    retriever = [PListRetriever sharedInstance];
    CGPoint pt = [[touches anyObject] locationInView: self];
        NSURL *target = [[NSURL alloc] initWithString:[retriever.plistDict valueForKey:@"url"]];
        [[UIApplication sharedApplication] openURL:target];
  }

The problem is right now, no matter where I touch in the View the Url is being opened. How do I determine if only just my label was touched?

like image 703
Sean McCully Avatar asked Mar 29 '10 15:03

Sean McCully


3 Answers

If you add the label to the class, you can do a hit-test on your view in the touch event with:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [[event allTouches] anyObject];
  if (CGRectContainsPoint([self.site frame], [touch locationInView:self.view]))
  {
    NSURL *target = [[NSURL alloc] ...];
    ...
  }
}

Also, don't forget to release the URL you allocate (otherwise you are leaking).

like image 157
Kevin Sylvestre Avatar answered Nov 06 '22 20:11

Kevin Sylvestre


You can do this without overriding touchesBegan. Use gesture recognizers.

UILabel *label = ...;
label.userInteractionEnabled = YES;
UITapGestureRecognizer *recognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)] autorelease];

[label addGestureRecognizer:recognizer];

- (void)tapAction {
  NSLog(@"tap performed");
}
like image 39
Eugene Avatar answered Nov 06 '22 21:11

Eugene


i think the best way for handle is to set flag for each uilabel part and then give the flag number from the code,

label.userInteractionEnabled = YES;


-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *touch = [touches anyobject];

    if(touch.view.tag == uurflagnumber)
    NSlog(@"touched");
} 
like image 24
mahyar Avatar answered Nov 06 '22 19:11

mahyar