NSMutableAttributedString可以修改UILabel的部分文字的颜色、字体等,也可以在UILabel里添加image展示。
1.改变颜色 range是需要修改颜色的文字范围
+ (NSMutableAttributedString *)changeColorWithColor:(UIColor *)color content:(NSString *)content range:(NSRange)range {
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:content];
[attributedStr addAttribute:NSForegroundColorAttributeName
value:color
range:range];
return attributedStr;
}
2.修改字体
+ (NSMutableAttributedString *)changeFontWithFont:(UIFont *)font content:(NSString *)content range:(NSRange)range {
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:content];
[attributedStr addAttribute:NSFontAttributeName value:font range:range];
return attributedStr;
}
3.UILabel里展示本地图片
+ (NSMutableAttributedString *)addLocalImageInsertTextWithImageName:(NSString *)imageName mutableAttributeString:(NSMutableAttributedString *)mutableAttributeString index:(NSInteger)index imageWidth:(CGFloat)imageWidth imageHeight:(CGFloat)imageHeight{
UIImage *image = [UIImage imageNamed:imageName];
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
attch.image = image;
attch.bounds = CGRectMake(0, -3, imageWidth, imageHeight);
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[mutableAttributeString insertAttributedString:string atIndex:index];
return mutableAttributeString;
}
4.设置UILabel行间距
+ (NSMutableAttributedString *)lineSpacingWithAttributedString:(NSMutableAttributedString *)str lineSpacing:(CGFloat)lineSpacing content:(NSString *)content {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, content.length)];
[paragraphStyle setLineSpacing:lineSpacing];//调整行间距
return str;
}