如何更改ios中特定单词的颜色

Rah*_*ini 1 objective-c uitableview ios

我搜索任何特定的词,如"上帝".我想改变那个特定的文字颜色应该改变不同的颜色.我试着在谷歌搜索,但我发现特定的单词颜色从单词链接的开头到结尾的特定索引值变化,这就是我的问题无法解决的原因.

请帮助我并更新我的代码以更改特定的单词文本颜色,即您在图像中看到的框中的单词.

谢谢

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UYLCellIdentifier forIndexPath:indexPath];
    [self configureCell:cell forRowAtIndexPath:indexPath];
     return cell;
}

- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell isKindOfClass:[UYLTextCellSearch class]])
    {
         UYLTextCellSearch *textCell = (UYLTextCellSearch *)cell;

         DataBase *DBContentDetail = [_sourceData objectAtIndex:indexPath.row];

         textCell.lineLabel.text = [NSString stringWithFormat:@"%@",DBContentDetail.dbtext];
        [textCell.lineLabel sizeToFit];
    }
}
Run Code Online (Sandbox Code Playgroud)

如何更改ios中特定单词的颜色

Sha*_*hai 10

NSString *text = @"In the begining God created heaven and earth. God is great.";

NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(God)" options:kNilOptions error:nil]; // Matches 'God' case SENSITIVE

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

// Change all words that are equal to 'God' to red color in the attributed string
[regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:0];
    [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
}];

textCell.lineLabel.attributedText = mutableAttributedString;
Run Code Online (Sandbox Code Playgroud)

有关NSAttributedString的更多信息