How to highlight search string in AutoComplete results for IOS5?

依然范特西╮ 提交于 2019-12-21 21:29:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/14601936/how-to-highlight-search-string-in-autocomplete-results-for-ios5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!