TTTAttributedLabe作為UILabel的替代蜂莉,可以輕松的渲染可變字符串,文中中加入嵌入鏈接混卵,手機號映穗,時間都可以得到相對應(yīng)的處理,項目地址TTTAttributedLabel,簡單看一下效果:
FlyElephant.png
普通Label:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 50)];
label.textColor = [UIColor whiteColor];
label.text = @"美國職業(yè)籃球聯(lián)賽(National Basketball Association幕随,簡稱NBA蚁滋,中文簡稱“美職籃”)于1946年6月6日在紐約成立,是由北美三十支隊伍組成的男子職業(yè)籃球聯(lián)盟赘淮,美國四大職業(yè)體育...";
label.backgroundColor = [UIColor redColor];
label.font = [UIFont systemFontOfSize:14];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
[self.view addSubview:label];
TTTAttributedLabel中的FlyElephant鏈接設(shè)置:
NSString *text = @"美國職業(yè)籃球聯(lián)賽(National Basketball Association辕录,簡稱NBA,中文簡稱“美職籃”)于1946年6月6日在紐約成立(FlyElephant)拥知,是由北美三十支隊伍組成的男子職業(yè)籃球聯(lián)盟踏拜,美國四大職業(yè)體育...";
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.reibang.com/users/24da48b2ddb3/latest_articles"] withRange:serviceRange];
實現(xiàn)TTTAttributedLabelDelegate協(xié)議:
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
[[UIApplication sharedApplication] openURL:url];
}
如果加入了其他手勢操作,會導(dǎo)致TTTAttributedLabel中的鏈接無法響應(yīng)低剔,因此需要在手勢的delegate中進行判斷:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([touch.view isKindOfClass:[TTTAttributedLabel class]]) {
return NO;
}
return YES;
}