2011-12-16 19 views
19

Ho due NSStrings: orgText e searchLetter.
Desidero evidenziare tutte le occorrenze della searchLetter nello orgText con un colore rosso.
Come posso ottenere lo NSRange di tutte le occorrenze dello searchLetter?
per esempio:Come ottenere tutto NSRange di un determinato carattere in una NSString?

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

voglio hightlight tutti "a" occorrenze in "abcahaiapaoiuiapplma" con il colore rosso.
Grazie.

risposta

55

Ho scritto questo metodo per il mio progetto - 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; 
} 

E nella mia categoria di 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]; 
} 
+0

Perfetto anche nel 2012 :) – NDY

+0

Penso che ci sia un extra "}" in giro, ma grande lavoro ancora nel '14 – dacopenhagen

+0

@dacopenhagen voi sono giusti. quel metodo è stato scritto per più parole :) – SAKrisT

2

Codice incidente a "SetTextColor" per MutableAttributeString

invece di esso utilizzare sotto il codice

NSDictionary *tempdict=[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],NSFontAttributeName,color,NSForegroundColorAttributeName, nil]; 
[mutableAttributedString setAttributes:tempdict range:NSMakeRange(range.location, [word length])]; 
6

Non vedo alcuna soluzione con espressioni regolari, quindi ne ho creato uno elegante, potrebbe essere utile per qualcuno in futuro.

- (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; 
    } 
} 
-1

questo è un modo più semplice di farlo

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

NOTA: questo aggiungerebbe solo attributi alla prima occorrenza della sottostringa –

Problemi correlati