February 27, 2014

I have a serious appreciation for NSAttributedString. Cocoa's string constructs, while initially complex, provide power that I wish every language had. I recently implemented a small demo application. The application's sole purpose is to display posts from the App.net global timeline. While the application was quite simple, I wanted to display hashtags embedded in posts in a different color.

Luckily NSAttributedString makes this quite simple. My approach required two steps. First, using a regular expression, find all words starting with '#'. Next, apply a predefined style to all hashtags in the post. The code below demonstrates the simplicity of hashtag highlighting using NSAttributedString.

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];

// this regular expression should probably be smarter, but it works
NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:@"#[a-zA-z0-9]+" options:0 error:nil];

[regEx enumerateMatchesInString:text options:0 range:NSMakeRange(0, [text length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

   NSRange range = [result rangeAtIndex:0];
   [string setAttributes:@{NSForegroundColorAttributeName: highlightColor} range:range];
}];