1. 程式人生 > >NSMutableAttributedString-富文本的使用

NSMutableAttributedString-富文本的使用

awd 一個 ini through writing edt str tin src

富文本的使用步驟如下:

1. 創建一個 NSMutableAttributedString 的對象

2.設置 屬性:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; --設置單個屬性

- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range; --設置多個屬性

其中,屬性的設置有如下可以選擇:

NSFontAttributeName	字號	UIFont 默認12
NSParagraphStyleAttributeName	段落樣式	NSParagraphStyle
NSForegroundColorAttributeName	前景色	UIColor
NSBackgroundColorAttributeName	背景色	UIColor
NSObliquenessAttributeName	字體傾斜	NSNumber
NSExpansionAttributeName	字體加粗	NSNumber 比例 0就是不變 1增加一倍
NSKernAttributeName	字間距	CGFloat
NSUnderlineStyleAttributeName	下劃線	1或0
NSUnderlineColorAttributeName	下劃線顏色	UIColor
NSStrikethroughStyleAttributeName	刪除線	1或0
NSStrikethroughColorAttributeName	刪除線顏色	UIColor
NSStrokeColorAttributeName	same as ForegroundColor	UIColor
NSStrokeWidthAttributeName	字體描邊	CGFloat
NSLigatureAttributeName	連筆字 沒看出效果	1或0
NSShadowAttributeName	陰影	NSShawdow
NSTextEffectAttributeName	設置文本特殊效果,目前只有圖版印刷效果可用	NSString
NSAttachmentAttributeName	設置文本附件,常用插入圖片	NSTextAttachment
NSLinkAttributeName	鏈接	NSURL (preferred) or NSString
NSBaselineOffsetAttributeName	基準線偏移	NSNumber
NSWritingDirectionAttributeName	文字方向 分別代表不同的文字出現方向等等,我想你一定用不到它 - -	@[@(1),@(2)]
NSVerticalGlyphFormAttributeName	水平或者豎直文本 在iOS沒卵用,不支持豎版	1豎直 0水平

3.給文本添加賦值 用 attributedText 這個字段

4.實例:

UILabel *attLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 300, 50)];
    attLabel.font = [UIFont systemFontOfSize:15];
    attLabel.textColor = [UIColor blueColor];
    [self.view addSubview:attLabel];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"夕陽無限好,只是近黃昏"];
    attLabel.attributedText = str;
    
    NSDictionary *attDic = @{NSFontAttributeName:[UIFont systemFontOfSize:20],
                             NSForegroundColorAttributeName:[UIColor redColor],
                             NSBaselineOffsetAttributeName: @(-1.5),
                             NSStrikethroughStyleAttributeName:@(1),
                             NSStrikethroughColorAttributeName:[UIColor yellowColor],
                             NSKernAttributeName:@(4)};
    [str addAttributes:attDic range:NSMakeRange(6, 3)];
    
    attLabel.attributedText = str;

5.效果圖:

技術分享

NSMutableAttributedString-富文本的使用