检查字符串是否包含主题标签,然后更改主题标签颜色

Sea*_*ean 2 string iphone twitter parsing ios5

我正在开发一个从twitter上获取推文的iPhone应用程序.我是通过Json做的,一切都很好.我正在寻找每条推文,看它是否包含一个标签,然后更改该特定标签的颜色.

例如:"这是一条推文#MYTWEET"

所以我希望"这是一条推文"是一种颜色而"#MYTWEET"是一种单独的颜色.我知道如何搜索主题标签,但我似乎无法弄清楚如何更改下面的文本.

编辑:

也没有特定的主题标签,因此它需要能够更改出现的任何主题标签的颜色.

All*_*ian 11

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 ...
Run Code Online (Sandbox Code Playgroud)

注意:如果您想知道如何显示字符串,这里有一个很好的开源项目:https://github.com/AliSoftware/OHAttributedLabel