美文网首页iOS
iOS-UILabel建立超链接

iOS-UILabel建立超链接

作者: 亦晴工作室 | 来源:发表于2016-08-24 15:48 被阅读1237次
        //原理展示
        //
        
        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建立超链接

        本文链接:https://www.haomeiwen.com/subject/plkosttx.html