2011-12-16 10 views
19

Tôi có hai NSStrings: orgTextsearchLetter.
Tôi muốn làm nổi bật mọi lần xuất hiện của tìm kiếmTốt hơn trong orgText với màu đỏ.
Làm cách nào để nhận được NSRange của tất cả các lần xuất hiện của searchLetter?
cho ví dụ:Làm thế nào để có được tất cả NSRange của một nhân vật cụ thể trong một NSString?

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

Tôi muốn làm nổi bật tất cả "a" xuất hiện trong "abcahaiapaoiuiapplma" với màu đỏ.
Cảm ơn.

Trả lời

55

tôi đã viết phương pháp này cho dự án của tôi - 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; 
} 

Và trong thể loại của tôi 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

Perfect cũng trong năm 2012 :) – NDY

+0

Tôi nghĩ rằng có thêm "}" nổi xung quanh, nhưng làm việc rất lớn vẫn còn trong '14 – dacopenhagen

+0

@dacopenhagen bạn đúng. phương pháp đó được viết cho nhiều từ :) – SAKrisT

2

Mã sụp đổ tại "setTextColor" cho MutableAttributeString

thay vì nó sử dụng mã bên dưới

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

Tôi không thấy bất kỳ giải pháp nào với cụm từ thông dụng, vì vậy tôi đã tạo một giải pháp thanh lịch, nó có thể hữu ích cho ai đó trong tương lai.

- (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

đây là một cách dễ dàng hơn để làm việc đó

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

LƯU Ý: điều này sẽ chỉ thêm thuộc tính vào lần xuất hiện chuỗi con đầu tiên –