0

我正在使用TTTAttributedLabel并设置文本,例如“带有#tag 和 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;
}];

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

4

1 回答 1

2

您可以使用这种方式更改 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;

更新字符串方法:

- (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;

}

于 2018-08-16T10:47:14.780 回答