Search code examples
iosobjective-cuitableviewnsstringnsrange

Handling NSRange In UITableViewCell


I'm having a bit of an issue with NSRange. I have a CommentViewController which works but I'm trying to have a tapGesture 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?


Solution

  • 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,message[@"text"].length);
    
    [regex enumerateMatchesInString:message[@"text"] 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;