iOS開(kāi)發(fā)富文本顯示-- NSMutableAttributedString
用NSString初始化:
NSMutableAttributedString * AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"當(dāng)臣臣愛(ài)上哲哲"];
常用的3種:
//為某一范圍內(nèi)文字添加一個(gè)屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
//為某一范圍內(nèi)文字添加多個(gè)屬性 - (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
//移除某范圍內(nèi)的某個(gè)屬性 - (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)];
//陰影 (直接對(duì)所有文字有效)
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)];
//設(shè)置文字排版方向, 0 表示橫排文本,1 表示豎排文本, iOS中只有橫排,0以外的未定義
[AttributedStr addAttribute:NSVerticalGlyphFormAttributeName value:@(1) range:NSMakeRange(NSUInteger loc, NSUInteger len)];
//字體傾斜,負(fù)數(shù)為左傾斜
[AttributedStr addAttribute:NSObliquenessAttributeName value:@(1) range:NSMakeRange(1, 2)];
[AttributedStr addAttribute:NSObliquenessAttributeName value:@(-1) range:NSMakeRange(5, 2)];
//橫向拉伸,負(fù)數(shù)為壓縮
[AttributedStr addAttribute:NSExpansionAttributeName value:@1 range:NSMakeRange(3, len)];
使用字典 直接添加多個(gè)屬性
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)];