iOS-NSAttributedString自定义文字变色

1.使用注意:

1.给UILabel设置attributedText了会导致给UILabel中text,font,textColor,shadowColor,shadowOffset,textAlignment,lineBreakMode这7个属性设置值时无效果。

2.这个框架的应用场景一般在图文混排和搜索功能中应用比较多。

2.需求:让文本标签文字部分变色

2.1.示例代码如下:

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource> // 遵守数据源协议
/**
 *  设置用于显示的 tableView
 */
@property (strong, nonatomic) UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.初始化 tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height)];

    // 2.设置数据源代理方法
    self.tableView.dataSource = self;
    
    // 3.把 tableView 添加到控制器的 view 上显示
    [self.view addSubview:self.tableView];
}
# pragma mark - 数据源方法 - 每组显示多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 40;
}
# pragma mark - 数据源方法 - 每行显示的具体内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.标识可重用标示符
    static NSString *ID = @"Sun";
    
    // 2.去缓存池当中找可重用 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 3.如果没有,下面开始创建 cell
    if (cell == nil) {
        
        // 3.1.创建 cell
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
        // 3.2.自定义一个字符串
        NSString *myStr = @"比尔吉沃特+晒太阳的仙人掌";
        // 3.3.初始化一个富文本属性
        NSMutableAttributedString *attrs = [[NSMutableAttributedString alloc] initWithString:myStr];
        // 3.4.指定变色文字的范围
        NSRange rang = [str rangeOfString:@"晒太阳的仙人掌"];
        // 3.5.1.定义随机色
        UIColor *myColor = [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
        // 3.5.2.给富文本添加属性
        [attrs addAttribute:NSForegroundColorAttributeName value:myColor range:rang];
        
        // 3.6.设置 cell 上的文字
        cell.textLabel.attributedText = attrs;
    }
    return cell;

}
@end

2.2.运行结果如下:

原文地址:https://www.cnblogs.com/sleepingSun/p/5150636.html