【问题标题】:How to change the color of a specific word in ios如何在ios中更改特定单词的颜色
【发布时间】:2014-09-18 11:02:47
【问题描述】:

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

【问题讨论】:

标签: ios objective-c uitableview


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    是的,您可以使用 iOS 7 中引入的“文本工具包框架”更改特定单词的颜色。

    注意语句“在模型-视图-控制器范式中,布局管理器是控制器。NSTextStorage 是 NSMutableAttributedString 的子类,提供模型的一部分,保存一串具有字体等属性的文本字符,样式,颜色”记录在这里:(https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html)

    否则您可以查看 WWDC 2013 的此视频 (https://developer.apple.com/videos/wwdc/2013/#210) 中给出的示例。

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 2021-12-01
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多