HalesEnchanted HalesEnchanted - 1 year ago 109
Objective-C Question

Handling NSRange In UITableViewCell

I'm having a bit of an issue with

. I have a
which works but I'm trying to have a
and change the the color of the text right after the @, like a twitter mention. For some reason, in some of the cells, all of the text changes color as opposed to just the mention. Here's the code:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:message[@"text"]];

NSArray *words=[message[@"text"] componentsSeparatedByString:@""];

for (NSString *word in words) {
if ([word hasPrefix:@"@"]) {
NSRange range=[message[@"text"] rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
[cell.bodyLabel setAttributedText:string];

What am I doing wrong and how do I include a gesture to the colored portion?

Answer Source

Have you try this

NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:message[@"text"]];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(@[A-Za-z0-9]*)" options:kNilOptions error:nil];

NSRange range = NSMakeRange(0,strFirst.length);

[regex enumerateMatchesInString:strFirst options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];

cell.bodyLabel.attributedText = attributedString;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download