添加轻击手势到UILabel的一部分

cdu*_*dub 6 iphone nsattributedstring uilabel ios uitapgesturerecognizer

我有一个像这样的NSAttributedString:

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

NSMutableAttributedString设置为UILabel,如下所示:

label.attributedText = str;
Run Code Online (Sandbox Code Playgroud)

如何在另一个视图控制器中为上面的字符串中的'@clickhere'做出一个轻击手势(或可点击的东西)?

谢谢!

Sha*_* TK 5

我认为,最好的方法是添加UIGestureRecognizer你的UILabel并验证你想要的框架.

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.
     }
}
Run Code Online (Sandbox Code Playgroud)