如何更改已替换的单词的颜色

时间:2014-06-28 06:46:23

标签: ios objective-c string colors uitextview

想一下语法检查器。如果我输入"我应该知道节目是今天。"它将成为"我应该知道它是今天。"有一个语法检查应用程序,将更换的部分变成红色。我想知道怎么做。

在你将我与其他问题联系起来之前,我已经看过他们了,他们都谈论了范围。范围需要一定数量的必须放置的字符,但是如果有100多个短语,如果它们得到纠正,则可以看到这是一个问题。我一直看到NSMutableString,但也有范围。

例如,以下是将用户输入(无论他输入什么内容)转换为字符串的代码。

NSString *input = _inputTextView.text;

这是一个正在改变的单词的例子。

inpput = [input stringByReplacingOccurencesOfString:@"(?wi)\\bshould of\\b" withString:@"should have" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];

这是使更正的字符串显示在另一个UITextView中的代码:

_outputTextView.text = input;

例如: 用户输入:我应该去商店。 输出:我应该去商店。

基本上以最简单的方式,我可以在上面的代码中放置一个代码来改变颜色吗?像一个选项:颜色:或什么?

1 个答案:

答案 0 :(得分:0)

这个让我感兴趣,所以我找到了一个快速的解决方案。

我对此进行了测试,看起来效果非常好。您需要使用属性字符串来存储颜色属性。

// define what you want to replace and what you want to replace it with
NSString *stringToReplace = @"(?wi)\\bshould of\\b";
NSString *newString = @"should have";

// get a mutable attributed string so that the color can be used as an attribute
NSMutableAttributedString *attributedInput = _inputTextView.attributedText.mutableCopy;

NSRange rangeToReplace;

do
{
    // check for occurrence
    rangeToReplace = [[attributedInput string] rangeOfString:stringToReplace options:NSRegularExpressionSearch];
    if(rangeToReplace.location != NSNotFound)
    {
        // create the range we're going to color
        NSUInteger locationToBeReplaced = rangeToReplace.location;
        NSUInteger replacedLength = newString.length;
        NSRange rangeToAddAttribute = NSMakeRange(locationToBeReplaced, replacedLength);

        // replace old string
        [attributedInput replaceCharactersInRange:rangeToReplace withString:newString];

        // color new string
        [attributedInput addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rangeToAddAttribute];
    }
}
while(rangeToReplace.location != NSNotFound); // continue until all occurrences have been replaced