iOS-UILabel建立超链接

    //原理展示
    //
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 300, 260)];
    [self.view addSubview:label];
    
    //设置下划线
    NSString *plainString = @"http://www.baidu.com";
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:plainString];
    
    [attrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attrString.length)];//下划线
    //下划线颜色
    [attrString addAttribute:NSUnderlineColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, attrString.length)];
    label.attributedText = attrString;
    
    
    //添加
    label.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealClickURL:)];
    [label addGestureRecognizer:tap];
}
-(void)dealClickURL:(UITapGestureRecognizer *)tap
{
    UILabel *label = (UILabel *)tap.view;
    NSLog(@"text = %@",label.text);
    
    if([label.text hasPrefix:@"http://"])
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:label.text]];
    }
    

}

你可能感兴趣的:(iOS-UILabel建立超链接)