iOS开发IOS网友们的篇章iOS新手学习

CJLabel图文混排一 ——UILabel富文本显示以及任意字

2016-04-20  本文已影响3778人  lele8446

CJLabel已经更新最新版本V2.1.2 ,相关文章介绍看这里CJLabel图文混排二 —— UILabel插入图片以及精确链点点击


在NSAttributedString出现之前,UILabel只能做简单的文本显示,如果要显示富文本我们只能通过Core Text来实现,同时UILabel的userInteractionEnabled属性默认是NO的,即不能响应用户的交互操作。在本文我通过UILabel的attributedText来显示富文本(关于对NSAttributedString的封装以及size信息的计算,可参照上一篇文章动态计算NSAttributedString的size大小),同时判断每次点击label时对应字符的NSRange位置信息,实现了任意字符的点击响应。


方法- addLinkString: linkAddAttribute: linkParameter: block:添加要响应点击事件的字符串,block为点击该字符串对应的回调事件;- removeLinkString:移除点击事件。

  - (void)addLinkString:(NSAttributedString *)linkString block:(CJLinkLabelModelBlock)linkBlock {
      CJLinkLabelModel *linkModel = [[CJLinkLabelModel alloc]initLinkLabelModelWithString:linkString range:[self getRangeWithLinkString:linkString] block:linkBlock];
      if (nil != linkModel) {
          [self.linkArray addObject:linkModel];
      }
  }

CJLinkLabelModel是自定义的点击链点model类,包含三个属性linkBlock(该链点的点击回调事件)、linkString(链点对应的字符串)、range(链点对应的NSRange信息)、parameter(可传递点击链点的相关参数:id,色值,字体大小等)。每添加一段能够响应点击事件的字符串,都新创建一个CJLinkLabelModel,并add到self.linkArray中。

设置CJLabel的属性self.userInteractionEnabled = YES,同时重写- touchesBegan: withEvent:方法

  - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
     UITouch * touch = touches.anyObject;
     //获取触摸点击当前view的坐标位置
     CGPoint location = [touch locationInView:self];
     //判断是否响应了点击事件
     if(![self needResponseTouchLabel:location]) {
        [self.nextResponder touchesBegan:touches withEvent:event];
     }
  }

- needResponseTouchLabel方法将点击坐标转化为对应的第index个字符,然后遍历self.linkArray数组,判断该字符是否在需响应点击事件的字符串数组内,是的话则响应点击回调,否则向self.nextResponder继续传递点击交互。

另外self.extendsLinkTouchArea可以设置是否加大点击响应范围,类似于UIWebView的链点点击效果,默认NO。

- removeLinkString:方法

  - (void)removeLinkString:(NSAttributedString *)linkString {
      __block NSUInteger index = 0;
      __block BOOL needRemove = NO;
     [self.linkArray enumerateObjectsUsingBlock:^(id num, NSUInteger idx, BOOL *stop){
          CJLinkLabelModel *linkModel = (CJLinkLabelModel *)num;
          if ([linkModel.linkString isEqualToAttributedString:linkString]) {
              index = idx;
              needRemove = YES;
              *stop = YES;
           }
      }];
      [self.linkArray removeObjectAtIndex:index];
  }
CJLabel的使用

最后附上demo地址

上一篇 下一篇

猜你喜欢

热点阅读