Search code examples
objective-cios5xcode4.5

How to highlight search string in AutoComplete results for IOS5?


Google autocomplete would bolden what we search

For example: If we search for hell we'll see "hell o"

I think I need attributed string, so my code is:

- (NSMutableAttributedString*) highlightSearchString:(NSString*)substringToHighlight{

    NSMutableAttributedString * mutableAttributedString = [[ NSMutableAttributedString alloc]initWithString:self];
    NSUInteger count = 0, length = [mutableAttributedString length];
    NSRange range = NSMakeRange(0, length);

    count = 0,
    length = [mutableAttributedString length];
    range = NSMakeRange(0, length);
    while(range.location != NSNotFound)
    {
        range = [[mutableAttributedString string] rangeOfString:substringToHighlight options:0 range:range];
        if(range.location != NSNotFound) {

            //[mutableAttributedString setTextColor:[UIColor blueColor] range:NSMakeRange(range.location, [word length])];
            NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
            NSDictionary * dict = @{NSFontAttributeName:boldFontName};
            NSRange  rangeHighlight = NSMakeRange(range.location, substringToHighlight.length);
            [mutableAttributedString setAttributes:dict range:rangeHighlight];
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++;
        }
    }
    return mutableAttributedString;
}

But it doesn't work because NSFontAttributeName is available only in iOS6.

After that I need to update the tableViewCell

cell.textLabel.text=text;

with something that take advantage of the atributed text.


Solution

  • Just use the CoreText definition for the font:

    UIFont *font = [UIFont boldSystemFontOfSize:12]; 
    CTFontRef ctFontRef = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
    NSDictionary * dict = @{(NSString *)kCTFontAttributeName : (__bridge id) ctFontRef};
    

    For the seconds problem:

    The default UILabel in the iOS SDK only supports NSAttributedString from iOS 6. Thus in iOS 5 you will either have to draw the NSAttributedString your self using CoreText of get some third part label that does support NSAttributedString like: TTTAttributedLabel.