TTTAttributedLabel 使用小记

黄景胜
2023-12-01

TTTAttributedLabel继承自UILabel,很方便基于现有代码进行修改,Star超过6K+,作者一直有更新,今天用了一下作点笔记。

 //设置高亮颜色

    label.highlightedTextColor = [UIColor greenColor];

    

    //检测url

    label.enabledTextCheckingTypes = NSTextCheckingTypeLink;

    

    //对齐方式

    label.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;

    

    //行间距

    label.lineSpacing = 8;

    

    //设置阴影

    label.shadowColor = [UIColor grayColor];

    

    label.delegate = self// Delegate

    //NO 不显示下划线

    label.linkAttributes = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NOforKey:(NSString *)kCTUnderlineStyleAttributeName];

    

    NSString *text = @"冷清风 赞了 王战 的说说";


    

    [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString*mutableAttributedString)

    {

        

        //设置可点击文字的范围

        NSRange boldRange = [[mutableAttributedString stringrangeOfString:@"冷清风" options:NSCaseInsensitiveSearch];

        

        //设定可点击文字的的大小

        UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:16];

        CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSizeNULL);

    

        if (font) {

            

            //设置可点击文本的大小

            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];

            

            //设置可点击文本的颜色

            [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor blueColorCGColorrange:boldRange];


            CFRelease(font);

            

        }

       return mutableAttributedString;

    }];

    

    //正则

    NSRegularExpression *regexp = NameRegularExpression();

    

    NSRange linkRange = [regexp rangeOfFirstMatchInString:text options:0 range:NSMakeRange(03)];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.exiucai.com/"]];

    

    //设置链接的url

    [label addLinkToURL:url withRange:linkRange];




 类似资料: