ios中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;

        

        //3.关键字高亮

        NSMutableAttributedString * mat = label.attributedText.mutableCopy;

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

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

        

        label.attributedText = mat;

    }

    

 

posted @ 2016-02-22 16:02  湘岳  阅读(956)  评论(0编辑  收藏  举报