iOS开发—使用TYAttributedLabel实现字体大小颜色各异并且带链接的文本

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Alexander_Wei/article/details/78872099

TYAttributedLabel是一个强大的属性文本控件。它支持富文本、图文混排显示;它支持行间距、字间距、自适应高度、指定行数;它支持添加高度自定义文本属性,支持添加属性文本、自定义链接,新增高亮效果显示(文字和背景);它还支持添加UIImage和UIView控件。

使用TYAttributedLabel实现字体大小、颜色各异并且带链接的文本:

    //属性文本生成器
    NSString* text = @"Not yet a Finnair Plus member?Learn more or sign up to start enjoying a world of benefits!";
    
    TYTextContainer *textContainer = [[TYTextContainer alloc] init];
    textContainer.text = text;
    textContainer.textColor = [UIColor grayColor];
    textContainer.font = [UIFont boldSystemFontOfSize:11];
    textContainer.linesSpacing = 0.5;
    
    //文字样式
    TYTextStorage *textStorage = [[TYTextStorage alloc]init];
    textStorage.range = [text rangeOfString:@"Learn more or sign up"];
    textStorage.font = [UIFont boldSystemFontOfSize:11];
    textStorage.textColor = [UIColor blueColor];
    [textContainer addTextStorage:textStorage];
    
    //下划线文字
    TYLinkTextStorage *linkTextStorage = [[TYLinkTextStorage alloc]init];
    linkTextStorage.range = [text rangeOfString:@"Learn more or sign up"];
    linkTextStorage.linkData = @"登录芬兰航空";
    //取消下划线
    linkTextStorage.underLineStyle = kCTUnderlineStyleNone;
    [textContainer addTextStorage:linkTextStorage];
    
    
    TYAttributedLabel *label = [[TYAttributedLabel alloc]initWithFrame:CGRectMake(15, 350, KWidth-30, 0)];
    label.backgroundColor = [UIColor clearColor];
    label.textContainer = textContainer;
    [label sizeToFit];
    //设置代理
    label.delegate = self;
    
    [self.view addSubview:label];

实现代理方法TYAttributedLabelDelegate:

//点击带链接文字“Learn more or sign up”
-(void)attributedLabel:(TYAttributedLabel *)attributedLabel textStorageClicked:(id<TYTextStorageProtocol>)textStorage atPoint:(CGPoint)point{
    
    if ([textStorage isKindOfClass:[TYLinkTextStorage class]]){
        
        NSString *linkStr = ((TYLinkTextStorage*)textStorage).linkData;
        
        if ([linkStr isEqualToString:@"登录芬兰航空"]) {
            
            [[ UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.finnair.com/cn/cn/plus"] options:@{} completionHandler:nil];
        }
        
    }
}


效果图:

猜你喜欢

转载自blog.csdn.net/Alexander_Wei/article/details/78872099