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

在iOS开发中,常常会有某一区间一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求,

了解到NSMuttableAttstring(带属性的字符串),来实现这些需求.


使用方法:

为某一范围内文字设置多个属性

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

为某一范围内文字添加某个属性

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

为某一范围内文字添加多个属性

- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

移除某范围内的某个属性

- (void)removeAttribute:(NSString *)name range:(NSRange)range;

2.     常见的属性及说明

字体

NSFontAttributeName 

段落格式 

NSParagraphStyleAttributeName 

字体颜色

NSForegroundColorAttributeName 

背景颜色

NSBackgroundColorAttributeName  

删除线格式

NSStrikethroughStyleAttributeName

下划线格式

NSUnderlineStyleAttributeName     

删除线颜色

NSStrokeColorAttributeName       

删除线宽度

NSStrokeWidthAttributeName

阴影

NSShadowAttributeName 

example1 :

   UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];

                    [self.view addSubview:label];

                    label.text = @"haha";

                    

                    NSAttributedString *attrStr =

                    [[NSAttributedString alloc]initWithString:label.text

                                                   attributes:

                     @{NSFontAttributeName:[UIFont systemFontOfSize:20.f],

                       NSForegroundColorAttributeName:[UIColor cyanColor],

                       NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle|NSUnderlinePatternSolid),

                       NSStrikethroughColorAttributeName:[UIColor blackColor]}];

                    label.attributedText = attrStr;

效果就是这样的

example2:

    NSString *str = @"哈哈哈(假日)";                    

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

                    [attributeStr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:[UIColor colorWithRed:0.206 green:0.309 blue:1.000 alpha:1.000]} range:NSMakeRange(4, 2)];

                    cell.textLabel.attributedText = attributeStr; 

哈哈哈(假日), 效果是这样的


更多详细请看: 点击打开苹果官方链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值