2

谷歌自动完成会加粗我们搜索的内容

例如:如果我们搜索地狱,我们会看到“ 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;

有一些利用归属文本的东西。

4

1 回答 1

3

只需使用字体的 CoreText 定义:

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

对于秒问题:

UILabeliOS SDK 中的默认设置仅支持NSAttributedStringiOS 6。因此,在 iOS 5 中,您要么必须NSAttributedString使用 CoreText 绘制自己,要么获取一些支持的第三方标签,NSAttributedString例如:TTTAttributedLabel

于 2013-01-30T10:45:44.223 回答