Skip to content

Instantly share code, notes, and snippets.

@psobko
Last active December 23, 2015 22:49
Show Gist options
  • Save psobko/6705823 to your computer and use it in GitHub Desktop.
Save psobko/6705823 to your computer and use it in GitHub Desktop.
Color a word in NSAttriburedString
//Modified from http://stackoverflow.com/questions/8533691/how-to-get-all-nsrange-of-a-particular-character-in-a-nsstring
- (NSMutableAttributedString*) setColor:(UIColor*)color word:(NSString*)word inText:(NSMutableAttributedString*)mutableAttributedString {
NSUInteger count = 0, length = [mutableAttributedString length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[mutableAttributedString string] rangeOfString:word options:0 range:range];
if(range.location != NSNotFound) {
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
return mutableAttributedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment