Sean
Sean

Reputation: 345

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.

Upvotes: 2

Views: 3663

Answers (3)

schickling
schickling

Reputation: 4240

If you're using an UILabel to display the string, you could use ActiveLabel.swift which is an UILabel drop-in replacement supporting Hashtags (#), Mentions (@) and URLs (http://) written in Swift.

enter image description here

Changing the color of usernames, hashtags and links is as simple as this:

label.textColor = .blackColor()
label.hashtagColor = .blueColor()
label.mentionColor = .greenColor()
label.URLColor = .redColor()

Disclaimer: I'm the author of the library.

Upvotes: 0

Alladinian
Alladinian

Reputation: 35686

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

Upvotes: 11

Nitin Alabur
Nitin Alabur

Reputation: 5812

 NSRange hashLocation = [tweetString rangeOfString:@"#MYTWEET"];
 if  (hashLocation.location == NSNotFound) 
      {
          //do coloring stuff here
      }

edit: I think you are looking to color a substring only. This is not possible in the current versions of iOS, but you can do so by creating a label for each color and placing them next to each other so that it reads like a single line of text.

Upvotes: 0

Related Questions