添加轻击手势到UILabel的一部分 [英] Add a tap gesture to a part of a UILabel

查看:530
本文介绍了添加轻击手势到UILabel的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的NSAttributedString:

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)];

NSMutableAttributedString设置为UILabel,如下所示:

The NSMutableAttributedString gets set to a UILabel like so:

label.attributedText = str;

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

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

谢谢!

推荐答案

我认为,最好的方法是将 UIGestureRecognizer 添加到 UILabel 并验证您想要的帧。

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

这篇关于添加轻击手势到UILabel的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆