label中的关键字高亮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了label中的关键字高亮相关的知识,希望对你有一定的参考价值。

一 、在初始化方法中把所有需要高亮关键字的label加入到labels数组中,并且把这些label原来字体的颜色加入到 labelTextColors中 ,代码如下

 self.labels = [NSArray arrayWithObjects:self.textLabel,self.detailTextLabel, nil];

   self.labelTextColors = [NSArray arrayWithObjects:kColor_Black,kColor_LightGray, nil];

二 、在layoutSubviews中加上这段代码

for (int i = 0; i < self.labels.count; i++) {

        UILabel * label = self.labels[i];

      //1.取出label原来字体的颜色

        UIColor *  originalColor = self.labelTextColors[i];

        //2.恢复原来颜色

        NSMutableAttributedString * originalMat = label.attributedText.mutableCopy;

        [originalMat setAttributes:@{NSForegroundColorAttributeName:originalColor}

                             range:[label.text rangeOfString:label.text]];

        

        label.attributedText = originalMat;

        

        //2.关键字高亮

        NSMutableAttributedString * mat = label.attributedText.mutableCopy;

        [mat setAttributes:@{NSForegroundColorAttributeName:[UIColor blueColor]}

                     range:[label.text rangeOfString:self.keyWords]];//keyWords就是需要高亮的关键字

        

        label.attributedText = mat;

    }

    

 

以上是关于label中的关键字高亮的主要内容,如果未能解决你的问题,请参考以下文章

简介原理基本使用

Elasticsearch查询结果高亮操作实战

3.6 Lucene基本检索+关键词高亮+分页

Asp如何将搜索结果中的关键字用高亮显示?

vue搜索实现 搜索关键字高亮

Linux中日志中的关键字高亮