在我们的开发中经常需要改变某段文本中部分文字的颜色,很多同学都比较头疼实现方法,我在开发中也遇到过,现封装了下,方便于大家使用。有两个版本一个是OC版,另一个是Swift版本。
先上图看效果:
Paste_Image.pngSwift版
//MARK 富文本部分字体飘灰
func setupAttributeString(text : NSString, highlightText : NSString) -> NSMutableAttributedString {
let hightlightTextRange = text.rangeOfString(highlightText as String)
let attributeStr = NSMutableAttributedString.init(string: text as String)
attributeStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(hexString: "#0000ff"), range: hightlightTextRange)
self.fileNameLabel?.lineBreakMode = .ByCharWrapping
self.fileNameLabel?.attributedText = attributeStr
return attributeStr
}
OC版
#pragma mark - 富文本部分字体飘灰
- (NSMutableAttributedString *)setupAttributeString:(NSString *)text highlightText:(NSString *)highlightText {
NSRange hightlightTextRange = [text rangeOfString:highlightText];
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
if (hightlightTextRange.length > 0) {
[attributeStr addAttribute:NSForegroundColorAttributeName
value:[UIColor colorWithHexString:@"#8c8c8c"]
range:hightlightTextRange];
[attributeStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13.0f] range:hightlightTextRange];
self.currentTitleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
self.currentTitleLabel.attributedText = attributeStr;
return attributeStr;
}else {
return [highlightText copy];
}
}
网友评论