ios中label的文字多种颜色显示

时间:2021-09-10 07:50:16

一 、在初始化方法中把所有需要高亮关键字的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;

}