【问题标题】:In TTTAttributedLabel two different text color not working在 TTTAttributedLabel 中,两种不同的文本颜色不起作用
【发布时间】:2018-08-16 08:00:23
【问题描述】:

我正在使用TTTAttributedLabel 并设置像 "text with #tag and www.example.com" 这样的文本。

我需要为 "www.example.com" 设置 redColor,为 "#tag" 设置 greenColor >。

但它设置为蓝色。

以下是我的代码:

 [label setText:@"text with #tag and www.example.com" afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
    NSRange rangeUrl = [[mutableAttributedString string] rangeOfString:@"www.example.com" options:NSCaseInsensitiveSearch];
    NSRange rangeTag = [[mutableAttributedString string] rangeOfString:@"#tag" options:NSCaseInsensitiveSearch];
    UIFont *boldSystemFont = [UIFont systemFontOfSize:IS_IPAD?16:14 weight:UIFontWeightRegular];
    CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
    if (font) {

        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:rangeUrl];
        [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:[UIColor redColor] range:rangeUrl];

        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:rangetag];
        [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:[UIColor greenColor] range: rangeTag];
        [mutableAttributedString addAttribute:(NSString *)kCTUnderlineColorAttributeName value:[UIColor clearColor] range: rangeTag];

        CFRelease(font);
    }
    return mutableAttributedString;
}];

如何解决这个问题。
请帮帮我!

【问题讨论】:

    标签: ios objective-c colors tttattributedlabel


    【解决方案1】:

    你可以使用这种方式来改变 NSMutableAttributedString 的文本颜色

    NSMutableAttributedString *attributedstring = [[NSMutableAttributedString alloc] initWithString:@"text with #tag and www.example.com"];
    attributedstring = [self updateString:attributedstring withChangeColorForText:@"#tag" withColor:[UIColor redColor]];
    attributedstring = [self updateString:attributedstring withChangeColorForText:@"www.example.com" withColor:[UIColor greenColor]];
    
    label.attributedText = attributedstring;
    

    updateString 方法:

    - (NSMutableAttributedString *)updateString:(NSMutableAttributedString *)mainAttributedString withChangeColorForText:(NSString*)searchText withColor:(UIColor*) color
    

    {

    NSRange range = [mainAttributedString.string rangeOfString:searchText options:NSCaseInsensitiveSearch];
    
    if (range.location != NSNotFound) {
        [mainAttributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
    
    return mainAttributedString;
    

    }

    【讨论】:

    • 它适用于“www.example.com”,但不适用于“#tag”。
    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2021-07-16
    • 2017-12-14
    • 2013-07-14
    • 2015-08-05
    相关资源
    最近更新 更多