iOS 富文本(NSMutableAttributedString)详解

在开发中,相信很多人会遇到在一个label中设置不同字体大小、不同颜色或者加下划线、删除线等问题呢,这里就是用到了NSMutableAttributedString(带属性的字符串)。
首先先了解一下NSMutableAttributedString:
初始化方法:

- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs;

初始化的方法和NSMutableString一样。

包含的几个基本方法:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;//为某一范围内文字添加某个属性
- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;//为某一范围内文字设置多个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;//移除某范围内的某个属性

常见的属性有:

 NSFontAttributeName  //字体

NSParagraphStyleAttributeName  //段落格式 

NSForegroundColorAttributeName  //字体颜色

NSBackgroundColorAttributeName  //背景颜色

NSStrikethroughStyleAttributeName //删除线格式

NSUnderlineStyleAttributeName     //下划线格式

NSStrokeColorAttributeName       //删除线颜色

NSStrokeWidthAttributeName   //删除线宽度

NSShadowAttributeName   //阴影

简单例子:

  NSString *string = @"我是一个中国人!";
    //初始化字符串
  NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:string];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:NSMakeRange(0,4)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 4)];
    [_label setAttributedText:attributedString];

运行结果:
这里写图片描述

另一个例子:

 NSString *string = @"我是一个中国人!";
    NSDictionary *attributeDict = @{NSFontAttributeName:[UIFont systemFontOfSize:15.0],NSForegroundColorAttributeName:[UIColor redColor],NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)};
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string attributes:attributeDict];
    [_label setAttributedText:str];

运行结果:
这里写图片描述

具体效果可以根据需求然后根据以上属性进行设置呢。

以上如有错误,请留言指出谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值