两种颜色NSMutableAttributedString

时间:2014-08-08 00:20:36

标签: ios objective-c nsattributedstring

目前,我正在为我的UILabel“喜欢”世界着色。

我想知道如何为标签中出现的所有其他颜色着色。目前正在努力应对这种能力,因为范围总会发生变化。

NSMutableAttributedString *mutableString = nil;
NSString *notificationText = [NSString stringWithFormat:@"%@ liked your Recap.", [[object objectForKey:@"from"] valueForKey:@"name"]];
mutableString = [[NSMutableAttributedString alloc] initWithString:notificationText];

NSString *pattern = @"(liked)";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

NSRange range = NSMakeRange(0,[notificationText length]);

[expression enumerateMatchesInString:notificationText options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    NSRange finalRange = [result rangeAtIndex:1];
    [mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:finalRange];
    cell.notificationUser.attributedText = mutableString;
    cell.notificationUser.font = RobotoMedium(15.0f);
    cell.notificationTime.font = RobotoRegular(14.0f);
}];

1 个答案:

答案 0 :(得分:0)

正如@rmaddy指出的那样,你可以先设置整个字符串的颜色,然后再改变下面的具体范围:

[mutableString addAttribute:NSForegroundColorAttributeName
                      value:[NSColor blueColor]
                      range:NSMakeRange(0, [mutableString length])];

[mutableString addAttribute:NSForegroundColorAttributeName 
                      value:[UIColor orangeColor] 
                      range:finalRange];