一段文字中的某一段内容需要将其变得更加突显出来,为了复杂多余的操作流程,便通过如下的方法将内容进行调整,更加简便方便。
/**
改变 label 文字中某段文字的颜色和大小
label 传入的文本内容(注:传入前要有文字)
oneIndex 从首位文字开始
endIndex 至末位文字结束
color 字体颜色
size 字体字号
*/
+ (void)YHLabelAttributedString:(UILabel *)label firstText:(NSString *)oneIndex toEndText:(NSString *)endIndex textColor:(UIColor *)color textSize:(CGFloat)size;
+ (void)YHLabelAttributedString:(UILabel *)label firstText:(NSString *)oneIndex toEndText:(NSString *)endIndex textColor:(UIColor *)color textSize:(CGFloat)size {
// 创建 Attributed
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:label.text];
// 需要改变的首位文字位置
NSUInteger firstLoc = [[noteStr string] rangeOfString:oneIndex].location;
// 需要改变的末位文字位置
// NSUInteger endLoc = [[noteStr string] rangeOfString:endIndex].location + 1;
NSUInteger endLoc = [[noteStr string] rangeOfString:endIndex].location + [[noteStr string] rangeOfString:endIndex].length;
// 需要改变的区间
NSRange range = NSMakeRange(firstLoc, endLoc - firstLoc);
// 改变颜色
[noteStr addAttribute:NSForegroundColorAttributeName value:color range:range];
// 改变字体大小及类型
[noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Regular" size:size] range:range];
// 为 label 添加 Attributed
[label setAttributedText:noteStr];
}
以上便是此次分享的全部内容,希望能对大家有所帮助!
网友评论