TTTAttributedLabel简单使用

作者: FlyElephant | 来源:发表于2016-05-09 19:48 被阅读1562次

    TTTAttributedLabe作为UILabel的替代,可以轻松的渲染可变字符串,文中中加入嵌入链接,手机号,时间都可以得到相对应的处理,项目地址TTTAttributedLabel,简单看一下效果:

    FlyElephant.png

    普通Label:
    <pre><code>UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 50)]; label.textColor = [UIColor whiteColor]; label.text = @"美国职业篮球联赛(National Basketball Association,简称NBA,中文简称“美职篮”)于1946年6月6日在纽约成立,是由北美三十支队伍组成的男子职业篮球联盟,美国四大职业体育..."; label.backgroundColor = [UIColor redColor]; label.font = [UIFont systemFontOfSize:14]; label.numberOfLines = 0; label.lineBreakMode = NSLineBreakByWordWrapping; [self.view addSubview:label];</code></pre>

    TTTAttributedLabel中的FlyElephant链接设置:

    NSString           *text  = @"美国职业篮球联赛(National Basketball Association,简称NBA,中文简称“美职篮”)于1946年6月6日在纽约成立(FlyElephant),是由北美三十支队伍组成的男子职业篮球联盟,美国四大职业体育...";
    TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20, 180, 300, 100)];
    label.textColor = [UIColor whiteColor];
    
    NSMutableAttributedString *atributeStr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
                                                  NSForegroundColorAttributeName:[UIColor whiteColor],
                                                  NSFontAttributeName :[UIFont systemFontOfSize:14]
                                              }];
    label.text            = atributeStr;
    label.backgroundColor = [UIColor redColor];
    label.font            = [UIFont systemFontOfSize:14];
    label.numberOfLines   = 0;
    label.linkAttributes       = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontOfSize:16.0f]};
    label.activeLinkAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontOfSize:16.0f]};
    NSRange serviceRange = [text rangeOfString:@"FlyElephant"];
    label.delegate = self;
    [self.view addSubview:label];
    [label addLinkToURL:[NSURL URLWithString:@"http://www.jianshu.com/users/24da48b2ddb3/latest_articles"] withRange:serviceRange];
    

    实现TTTAttributedLabelDelegate协议:
    <pre><code>-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url { [[UIApplication sharedApplication] openURL:url]; }</code></pre>
    如果加入了其他手势操作,会导致TTTAttributedLabel中的链接无法响应,因此需要在手势的delegate中进行判断:
    <pre><code>`

    • (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
      if ([touch.view isKindOfClass:[TTTAttributedLabel class]]) {
      return NO;
      }
      return YES;
      }`</code></pre>

    相关文章

      网友评论

        本文标题:TTTAttributedLabel简单使用

        本文链接:https://www.haomeiwen.com/subject/sbperttx.html