Created
April 17, 2013 17:01
-
-
Save odrobnik/5405993 to your computer and use it in GitHub Desktop.
highlight string inside attributed string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSAttributedString *)attributedStringWithString:(NSString *)string highlightedwithOccurencesOfString:(NSString *)stringToHighlight inColor:(DTColor *)color | |
{ | |
// build an attributed string to start with | |
// font | |
DTCoreTextFontDescriptor *fontDesc = [[DTCoreTextFontDescriptor alloc] init]; | |
fontDesc.fontFamily = @"Helvetica"; | |
fontDesc.pointSize = 20; | |
// paragraph style | |
DTCoreTextParagraphStyle *paraStyle = [DTCoreTextParagraphStyle defaultParagraphStyle]; | |
// convert to CT objects | |
CTFontRef font = [fontDesc newMatchingFont]; | |
CTParagraphStyleRef para = [paraStyle createCTParagraphStyle]; | |
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:CFBridgingRelease(para), (id)kCTParagraphStyleAttributeName, CFBridgingRelease(font), (id)kCTFontAttributeName, nil]; | |
// construct base string | |
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string attributes:attributes]; | |
// find first occurrence of search string in source string | |
NSRange range = [string rangeOfString:stringToHighlight]; | |
while(range.location != NSNotFound) | |
{ | |
// highlight this range | |
[attributedString addAttribute:DTBackgroundColorAttribute value:(id)[color CGColor] range:range]; | |
// find next | |
range = [string rangeOfString:stringToHighlight options:0 range:NSMakeRange(range.location + 1, [string length] - range.location - 1)]; | |
} | |
return attributedString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment