修改 UILabel 文字中某段文字的颜色和大小 - iOS

一段文字中的某一段内容需要将其变得更加突显出来,为了复杂多余的操作流程,便通过如下的方法将内容进行调整,更加简便方便。

GitHub - 声明
GitHub - 实现

/**
 改变 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];
}

以上便是此次分享的全部内容,希望能对大家有所帮助!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容