如何在IOS5的“自动完成"结果中突出显示搜索字符串? [英] How to highlight search string in AutoComplete results for IOS5?

查看:54
本文介绍了如何在IOS5的“自动完成"结果中突出显示搜索字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google自动完成功能会加粗我们搜索的内容

Google autocomplete would bolden what we search

例如:如果我们搜索 hell ,我们会看到" hell o"

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

但是它不起作用,因为NSFontAttributeName仅在iOS6中可用.

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

之后,我需要更新tableViewCell

After that I need to update the tableViewCell

cell.textLabel.text=text;

带有一些利用附带文字的内容.

with something that take advantage of the atributed text.

推荐答案

只需对字体使用CoreText定义:

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

对于秒数问题:

iOS SDK中的默认UILabel仅支持iOS 6中的NSAttributedString. 在iOS 5上,您将不得不使用CoreText绘制NSAttributedString您自己的自己,以获得一些支持NSAttributedString的第三方标签,例如:

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.

这篇关于如何在IOS5的“自动完成"结果中突出显示搜索字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆