Search code examples
iphonestringparsingios5twitter

Check if string contains a hashtag and then change hashtag color


Im developing an iPhone app that fetches tweets from twitter. I'm doing this through Json and everything is working fine. I'm looking to search each tweet and see if it contains a hashtag and then change the color of that specific tag.

For example : "This is a tweet #MYTWEET"

So I want "This is a tweet" to be one color and "#MYTWEET" to be a separate color. I know how to search for a hashtag but I can't seem to figure out how to change just the text following.

EDIT:

There is no specific hashtag either, so It needs to be able to change the color of any hashtag that appears.


Solution

  • NSString *tweet = @"This is a tweet #MYTWEET";
    
    NSArray *words = [tweet componentsSeparatedByString:@" "];
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:tweet];
    
    for (NSString *word in words) {
    
        if ([word hasPrefix:@"#"]) {
    
            // Colour your 'word' here
            NSRange matchRange = [tweet rangeOfString:word];
    
            [attrString addAttribute:kCTForegroundColorAttributeName 
                               value:[UIColor redColor] 
                               range:matchRange]; 
            // Remember to import CoreText framework (the constant is defined there)
    
        }
    }
    
    //Display your attributed string ...
    

    Note: If you're wondering how to display the string, here is one nice open source project : https://github.com/AliSoftware/OHAttributedLabel