iOS猿媛圈iOS开发札记iOS干货

TTTAttributedLabel简单使用

2016-05-09  本文已影响1562人  FlyElephant

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>`

上一篇 下一篇

猜你喜欢

热点阅读