如何在IOS5的自动完成结果中突出显示搜索字符串?

时间:2013-01-30 10:37:37

标签: objective-c ios5 xcode4.5

Google自动填充功能会阻止我们搜索的内容

例如:如果我们搜索 hell ,我们会看到“地狱 o”

我想我需要归因于字符串,所以我的代码是:

- (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中可用。

之后我需要更新tableViewCell

cell.textLabel.text=text;

利用分配文本的东西。

1 个答案:

答案 0 :(得分:3)

只需使用字体的CoreText定义:

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的第三部分标签,如:TTTAttributedLabel