iOS 实现lable的最后一个字体单独改变颜色

具体代码的实现:

第一步: 创建一个工具类Tool

①. 在其.h文件中声明这样一个方法:

+ (NSMutableAttributedString *)changeCharColor:(NSString*)str;

②. 在.m中写方法的具体实现:(注意要在.m中导入#import <UIKit/UIKit.h>这个系统的头文件

+ (NSMutableAttributedString *)changeCharColor:(NSString*)str

{

    

    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:str];

    

    [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:248/255.0 green:27/255.0 blue:69/255.0 alpha:1]} range:NSMakeRange(str.length-1, 1)];

    

    return attStr;

    

}

第二步:在有label的那个类中实现字体颜色的改变

①. 导入#import "Tool.h"这个工具类的头文件

②. 代码的具体实现:

- (void)viewDidLoad

{

    [super viewDidLoad];

    //先把我们想要改变的那个字体的颜色发生改变

     NSMutableAttributedString*str=[Tool changeCharColor:@"高贺"];

    //然后把改变颜色后的字体赋值给label

      self.label.attributedText=str;;

 }

原文地址:https://www.cnblogs.com/gaohe/p/4497885.html