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

标签 ios objective-c uitableview

我搜索了任何特定的词,例如“上帝”。我想更改特定单词的文本颜色应该更改为不同的颜色。我尝试在谷歌上搜索,但我发现特定索引值的特定单词颜色从单词的开头到结尾发生变化 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];
    }
}

How to change the color of a specific word in ios

最佳答案

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/

相关文章:

ios - 委托(delegate)传递数据无响应

iphone - iPhone Facebook 3.0 主页制作攻略

api - Swift 4 tableView API 分页

ios - indexPath.row 返回最后一个可见单元格,并且没有调用 didSelectRowAtIndexPath

iphone - MKOverlay 无法顺利调整大小

ios - 从应用程序调用时更改状态栏的颜色

ios - 我的动画 JPG 不会发布

iphone - MKMapView 一次加载所有注释 View (包括那些在当前矩形之外的 View )

objective-c - 如何判断 UITableView 何时完成 ReloadData?

ios - DynamicCastClassUnconditional 与自定义单元类