19

と の 2 つの NSString がorgTextありsearchLetterます。で searchLetter が出現するたびに赤い色
で強調表示したいと思います。のすべての出現 を取得するにはどうすればよいですか? 例:orgText
NSRangesearchLetter

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

「abcahaiapaoiuiapplma」のすべての「a」を赤色で強調表示したいと思います。
ありがとう。

4

4 に答える 4

55

私は自分のプロジェクト用にこのメソッドを書きました - SUITextView with highlight :

- (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];
}
于 2011-12-16T12:05:55.470 に答える
7

正規表現を使用した解決策は見当たらないので、エレガントなものを作成しました。将来誰かに役立つかもしれません。

- (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;
    }
}
于 2014-06-20T10:21:04.360 に答える
2

MutableAttributeStringの「setTextColor」でコードがクラッシュする

代わりに以下のコードを使用してください

NSDictionary *tempdict=[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
[mutableAttributedString setAttributes:tempdict range:NSMakeRange(range.location, [word length])];
于 2013-02-05T10:53:44.247 に答える