Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a tap gesture to a part of a UILabel

I have a NSAttributedString like so:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"];
NSInteger length = str.length;
[str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)];

The NSMutableAttributedString gets set to a UILabel like so:

label.attributedText = str;

How do I make a tap gesture (or something clickable) to another viewcontroller for the words '@clickhere in the string above?

Thanks!

like image 928
cdub Avatar asked Jan 19 '15 05:01

cdub


2 Answers

I think, the best way is adding the UIGestureRecognizer to your UILabel and validate the frame that you would like.

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[_yourLabel addGestureRecognizer:singleTap];

- (void)handleTap:(UITapGestureRecognizer *)tapRecognizer
{
    CGPoint touchPoint = [tapRecognizer locationInView: _yourLabel];

    //Modify the validFrame that you would like to enable the touch
    //or get the frame from _yourLabel using the NSMutableAttributedString, if possible
    CGRect validFrame = CGRectMake(0, 0, 300, 44);

    if(YES == CGRectContainsPoint(validFrame, touchPoint)
     {
        //Handle here.
     }
}
like image 196
Shamsudheen TK Avatar answered Sep 30 '22 15:09

Shamsudheen TK


Simply first add a gesture to your label

[label setUserInteractionEnabled:YES];
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
[label addGestureRecognizer:gesture];

control your gesture area in the below method

- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
    static CGRect touchableRect = CGRectMake(100.0f, 0.0f, 100.0f, 50.0f); // Give your rect as you need.
    CGPoint touchPoint = [gestureRecognizer locationInView:self.view];
    if (CGRectContainsPoint(touchableRect, touchPoint))
    {
       //User has tap on where you want. Do your other stuff here
    }
}
like image 38
Tapas Pal Avatar answered Sep 30 '22 15:09

Tapas Pal