Как получить все NSRange конкретного символа в NSString? - PullRequest
19 голосов
/ 16 декабря 2011

У меня есть две строки NSS: orgText и searchLetter.
Я хочу выделить все вхождения searchLetter в orgText красным цветом.
Как я могу получить NSRange всех вхождений searchLetter?
например:

suppose: orgText = "abcahaiapaoiuiapplma"
         searchLetter = "a".

Я хочу выделить все "a" вхождения в "abcahaiapaoiuiapplma" красным цветом.
Спасибо.

Ответы [ 4 ]

55 голосов
/ 16 декабря 2011

Я написал этот метод для своего проекта - SUITextView с подсветкой :

- (NSMutableAttributedString*) setColor:(UIColor*)color word:(NSString*)word inText:(NSMutableAttributedString*)mutableAttributedString {

    NSUInteger count = 0, length = [mutableAttributedString length];
    NSRange range = NSMakeRange(0, length);

    while(range.location != NSNotFound)
    {
        range = [[mutableAttributedString string] rangeOfString:word options:0 range:range];
        if(range.location != NSNotFound) {
            [mutableAttributedString setTextColor:color range:NSMakeRange(range.location, [word length])];
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++; 
        }
    }

    return mutableAttributedString;
}

И в моей категории NSMutableAttributedString:

- (void) setTextColor:(UIColor*)color range:(NSRange)range {
    // kCTForegroundColorAttributeName
    [self removeAttribute:(NSString*)kCTForegroundColorAttributeName range:range]; // Work around for Apple leak
    [self addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)color.CGColor range:range];
}
7 голосов
/ 20 июня 2014

Я не вижу ни одного решения с регулярным выражением, поэтому я создал элегантное, оно может пригодиться кому-то в будущем.

- (BOOL)highlightString:(NSString *)string inText:(NSMutableAttributedString *)attributedString withColour:(UIColor *)color {
    NSError *_error;
    NSRegularExpression *_regexp = [NSRegularExpression regularExpressionWithPattern:string options:NSRegularExpressionCaseInsensitive error:&_error];
    if (_error == nil) {
        [_regexp enumerateMatchesInString:attributedString.string options:NSMatchingReportProgress range:NSMakeRange(0, attributedString.string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
            if (result.numberOfRanges > 0) {
                for (int i = 0; i < result.numberOfRanges; i++) {
                    [attributedString addAttribute:NSBackgroundColorAttributeName value:color range:[result rangeAtIndex:i]];
                }
            }
        }];
        return TRUE;
    } else {
        return FALSE;
    }
}
2 голосов
/ 05 февраля 2013

Сбой кода в "setTextColor" для MutableAttributeString

вместо использования кода ниже

NSDictionary *tempdict=[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
[mutableAttributedString setAttributes:tempdict range:NSMakeRange(range.location, [word length])];
0 голосов
/ 01 сентября 2015

это более простой способ сделать это

NSString *str = @"hello world";
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
[attr addAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} 
              range:[str rangeOfString:@"world"]];
...