使用NSMutableAttributedString 实现富文本(不同颜色字体、下划线等)

在iOS开发中,NSMutableAttributedString用于实现文本的丰富样式,如改变颜色、字体和添加下划线等效果。本文介绍了两种初始化方法,通过设置特定属性字典来实现文本的格式化。示例代码包括添加删除线的展示,帮助开发者理解和运用此技术。
摘要由CSDN通过智能技术生成

开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。NSMuttableAttstring(带属性的字符串),上面的一些需求都可以很简便的实现。
1.实例化方法有两种:
使用字符串来初始化
①:- (id)initWithString:(NSString *)str;
例如:
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"满1000减60的优惠券一张"];

②初始化的同时,将其属性也进行改变
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;

例子:

NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [UIFont systemFontOfSize:15.0],NSFontAttributeName,
                                    [UIColor redColor],NSForegroundColorAttributeName,nil];
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"满1000减60的优惠券一张" attributes:attributeDict];

使用方法①进行初始化时,初始化完后要再利用相关的方法进行属性的设置,常使用的方法如下:

为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值