TTTAttributedLabel实现点击label文字进行跳转

需求

点击Label中的某些文字实现跳转界面或者URL,使用TTTAttributedLabel实现,步骤如下:
  1. 安装

    推荐使用CocoaPods安装

    打开终端,cd 到你们的项目文件夹,在你们项目的Podfile文件里面添加一行:

    pod 'TTTAttributedLabel'

    然后,终端执行命令

    pod install

  1. 使用

    1.遵守 TTTAttributedLabelDelegate 代理协议

    2.设置基本的属性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    NSString *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.实现协议方法

    1
    2
    3
    4
    5
    6
    -(void) attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    [[UIApplication sharedApplication] openURL:url];
    }
这个人很帅<br>他什么都不想说<br>