iOS同一label显示多种格式(富文本)

iOS开发富文本显示-- NSMutableAttributedString

用NSString初始化:
NSMutableAttributedString * AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"当臣臣爱上哲哲"];

常用的3种:

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

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

属性:
//字体
[AttributedStr addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:25.0]
range:NSMakeRange(1, 2)];
[AttributedStr addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:25.0]
range:NSMakeRange(5, 2)];
//字体颜色
[AttributedStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(1, 2)];
//下划线
[AttributedStr addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:NSUnderlineStyleDouble]
range:NSMakeRange(1, 2)];
//背景颜色
[AttributedStr addAttribute:NSBackgroundColorAttributeName
value:[UIColor yellowColor]
range:NSMakeRange(NSUInteger loc, NSUInteger len)];
//删除线格式
[AttributedStr addAttribute:NSStrikethroughStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:NSMakeRange(NSUInteger loc, NSUInteger len)];
//删除线颜色
[AttributedStr addAttribute:NSStrikethroughColorAttributeName
value:[UIColor blueColor]
range:NSMakeRange(NSUInteger loc, NSUInteger len)];
//文字描边颜色和宽度
(PS:需要搭配显示)
[AttributedStr addAttribute:NSStrokeColorAttributeName
value:[UIColor greenColor]
range:NSMakeRange(5, 2)];
[AttributedStr addAttribute:NSStrokeWidthAttributeName
value:@3
range:NSMakeRange(5, 2)];
//阴影 (直接对所有文字有效)
NSShadow *shadow3 = [[NSShadow alloc] init];
shadow3.shadowOffset = CGSizeMake(9, 8);
shadow3.shadowBlurRadius = 0.5;
shadow3.shadowColor = [UIColor redColor];
[AttributedStr addAttribute:NSShadowAttributeName value:shadow3 range:NSMakeRange(NSUInteger loc, NSUInteger len)];
//设置文字排版方向, 0 表示横排文本,1 表示竖排文本, iOS中只有横排,0以外的未定义
[AttributedStr addAttribute:NSVerticalGlyphFormAttributeName value:@(1) range:NSMakeRange(NSUInteger loc, NSUInteger len)];
//字体倾斜,负数为左倾斜
[AttributedStr addAttribute:NSObliquenessAttributeName value:@(1) range:NSMakeRange(1, 2)];
[AttributedStr addAttribute:NSObliquenessAttributeName value:@(-1) range:NSMakeRange(5, 2)];
//横向拉伸,负数为压缩
[AttributedStr addAttribute:NSExpansionAttributeName value:@1 range:NSMakeRange(3, len)];

使用字典 直接添加多个属性
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize:15.0],NSFontAttributeName, [UIColor redColor],NSBackgroundColorAttributeName, [NSNumber numberWithInt:NSUnderlineStyleSingle],NSUnderlineStyleAttributeName,[NSNumber numberWithInt:NSUnderlinePatternSolid],NSStrikethroughStyleAttributeName, nil];

[AttributedStr addAttributes:dic range:NSMakeRange(NSUInteger loc, NSUInteger len)];

你可能感兴趣的:(iOS同一label显示多种格式(富文本))