需求
点击Label中的某些文字实现跳转界面或者URL,使用TTTAttributedLabel实现,步骤如下:
安装
推荐使用CocoaPods安装
打开终端,cd 到你们的项目文件夹,在你们项目的Podfile文件里面添加一行:
pod 'TTTAttributedLabel'
然后,终端执行命令
pod install
使用
1.遵守 TTTAttributedLabelDelegate 代理协议
2.设置基本的属性
12345678910111213141516171819NSString *text = @"点其他的字都没有用,点我才能跳转";TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20, 200,300, 50)];label.textColor = [UIColor whiteColor];NSMutableAttributedString *atributeStr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName :[UIFont systemFontOfSize:14]}];label.text = atributeStr;label.backgroundColor = [UIColor grayColor];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:@"点我才能跳转"];label.delegate = self;[self.view addSubview:label];[label addLinkToURL:[NSURL URLWithString:@"http://www.baidu.com/"] withRange:serviceRange];3.实现协议方法
123456-(void) attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {[[UIApplication sharedApplication] openURL:url];}