我搜索了任何特定的词,例如“上帝”。我想更改特定单词的文本颜色应该更改为不同的颜色。我尝试在谷歌上搜索,但我发现特定索引值的特定单词颜色从单词的开头到结尾发生变化 Link这就是我的问题没有解决的原因。
请帮助我并更新我的代码以更改特定单词的文本颜色,即您在图片中看到的框中的单词。
谢谢
- (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];
}
}
最佳答案
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;
更多关于 NSAttributedString
关于ios - 如何更改ios中特定单词的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25910926/