Ios 两种颜色NSMutableAttributeString
目前,我正在我的UILabel中给世界涂上“喜欢”的颜色 我想知道如何给标签上出现的其他东西上色。目前,由于范围不断变化,该功能正处于困境Ios 两种颜色NSMutableAttributeString,ios,objective-c,nsattributedstring,Ios,Objective C,Nsattributedstring,目前,我正在我的UILabel中给世界涂上“喜欢”的颜色 我想知道如何给标签上出现的其他东西上色。目前,由于范围不断变化,该功能正处于困境 NSMutableAttributedString *mutableString = nil; NSString *notificationText = [NSString stringWithFormat:@"%@ liked your Recap.", [[object objectForKey:@"from"] valueForKey:@"name"]
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);
}];
正如@rmaddy指出的,您可以先设置整个字符串的颜色,然后像下面这样更改特定范围:
[mutableString addAttribute:NSForegroundColorAttributeName
value:[NSColor blueColor]
range:NSMakeRange(0, [mutableString length])];
[mutableString addAttribute:NSForegroundColorAttributeName
value:[UIColor orangeColor]
range:finalRange];
创建字符串时,将基础颜色作为初始属性传递。然后将第二种颜色应用于所需零件。