在NSTextView中计算和更改字符串出现的文本颜色

时间:2014-10-30 20:40:05

标签: objective-c nstextview nsrange find-occurrences

我有一个任务,我需要计算日志文件中出现的错误,我知道如何做到这一点。现在我试图改变这些事件的字体颜色。我有点工作,但它不会将整个单词更改为所需的颜色,并且对于该字符串的下一次出现,它会移动超过3个字符。 见下图。

enter image description here

我搜索了这个词" Checked"它给了我这些结果。

以下是我正在使用的代码

NSArray * lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    wordresult = [lines componentsJoinedByString:@""];





if (occS2 == 1)
    {
        NSString * box2 = [_occSearchTwoTextBox stringValue];
        NSUInteger countFatal = 0, length4 = [wordresult length];
        NSRange range4 = NSMakeRange(0, length4);
        while(range4.location != NSNotFound)
        {
            range4 = [wordresult rangeOfString: box2 options:NSCaseInsensitiveSearch range:range4];

            [self.stringLogTextView setTextColor:[NSColor redColor] range:range4];
            NSLog(@"Occurance Edited");

            if(range4.location != NSNotFound)
            {
                range4 = NSMakeRange(range4.location + range4.length, length4 - (range4.location + range4.length));
                countFatal++;
            }
        }
        NSString * FatalCount = [NSString stringWithFormat:@"%lu", (unsigned long)countFatal];
        [_customSearchTwoTextBox setStringValue:FatalCount];
    }

任何人都可以指出我为什么要转移它?我只能假设它与我的范围有关,但我不知道该怎么做才能解决。

感谢每个人的时间!

1 个答案:

答案 0 :(得分:0)

我不确定为什么你的方法不能正常工作,但我会采用不同的方式。使用enumerateSubstringsInRange:options:usingBlock :,您可以逐字枚举您的字符串,并获取传入该方法的每个单词的范围。如果单词是"选中",您可以增加计数并设置可变属性字符串范围的属性。以下是如何使用该方法的示例

    NSString *theText = @"] Tables initialized\n]Database version Checked\n]Got login id-1\n] Tables initialized\n]Database version Checked\n]Got login id-1\n] Tables initialized\n]Database version Checked\n]Got login id-1\n";
    NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc] initWithString:theText];
    NSDictionary *dict = @{NSForegroundColorAttributeName:[NSColor greenColor]};

    __block int count = 0;
    [theText enumerateSubstringsInRange:NSMakeRange(0, theText.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        if ([substring isEqualToString:@"Checked"]) {
            [attrib setAttributes:dict range:substringRange];
            count ++;
        };
    }];

    self.textView.textStorage.attributedString = attrib;
    NSLog(@"count is: %d",count);

enter image description here

相关问题