iOS-NSAttributedString自定义文字变色

本文介绍在iOS开发中如何使用NSAttributedString为UILabel中的特定文本部分设置颜色,通过示例代码展示了如何实现文本部分变色的效果,适用于图文混排和搜索功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.运行结果如下:

876152-20160122111510968-453070035.png

转载于:https://www.cnblogs.com/sleepingSun/p/5150636.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值