ios – 为UILabel的一部分添加点击手势

前端之家收集整理的这篇文章主要介绍了ios – 为UILabel的一部分添加点击手势前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个像这样的NSAttributedString:
  1. NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"];
  2. NSInteger length = str.length;
  3. [str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)];

NSMutableAttributedString设置为UILabel,如下所示:

  1. label.attributedText = str;

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

谢谢!

解决方法

我认为,最好的方法是将UIGestureRecognizer添加到您的UILabel并验证您想要的帧.
  1. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
  2. [_yourLabel addGestureRecognizer:singleTap];
  3.  
  4. - (void)handleTap:(UITapGestureRecognizer *)tapRecognizer
  5. {
  6. CGPoint touchPoint = [tapRecognizer locationInView: _yourLabel];
  7.  
  8. //Modify the validFrame that you would like to enable the touch
  9. //or get the frame from _yourLabel using the NSMutableAttributedString,if possible
  10. CGRect validFrame = CGRectMake(0,300,44);
  11.  
  12. if(YES == CGRectContainsPoint(validFrame,touchPoint)
  13. {
  14. //Handle here.
  15. }
  16. }

猜你在找的iOS相关文章