Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle touch event on UILabel as subview of UITableViewCell?

My app has a custom UITableView. In the cellForRowAtIndexPath delegate method of its UIViewController I am instantiating custom UITableViewCell objects that contain multiple custom UILabels (actually a sub-class of OHAttributedLabel) as subviews of the content view.

I have tried setting userInteractionEnabled = YES on the label, then adding touch events in the view controller, but that isn't working.

Ideas?

Thanks

like image 615
Bama91 Avatar asked Aug 14 '11 20:08

Bama91


3 Answers

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
      UITouch *touch = [[event allTouches] anyObject];
      if (CGRectContainsPoint([self.site frame], [touch locationInView:self.view])){
       //do whatever you want
     }
}

Or

UILabel *label = =[UILabel alloc]init];
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =
[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)]     autorelease];
[label addGestureRecognizer:tapGesture];
like image 75
Praveen-K Avatar answered Nov 15 '22 17:11

Praveen-K


A UILabel isn't a UIControl so you won't get events on UIControlEventTouchUpInside or similar. Why not use a button instead? You can make it look exactly like a label.

Regardless you will probably need to set addTarget:action:forControlEvents: and tag on the UIButton in your cellForRowAtIndexPath: method. In that method, detect which cell's button was tapped by examining the tag value.

If you must use UILabel then you need to subclass it and intercept the touchesBegan/touchesEnded methods (inherited from UIResponder) to detect UIControlEventTouchUpInside yourself.

like image 26
Adam Eberbach Avatar answered Nov 15 '22 18:11

Adam Eberbach


Problem in OHAttributedLabel. This label also handles tap on links. So for handle tap on any point of label (not just link) you must

self.textLabel.onlyCatchTouchesOnLinks = NO;

Where self.textLabel is your OHAttributedLabel. And don't forget of userInteractionEnabled.

like image 32
surfrider Avatar answered Nov 15 '22 17:11

surfrider