1. 程式人生 > >iOS使用NSMutableAttributedString 實現富文字(不同顏色字型、劃線等等)

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 = [[UILabelalloc] initWithFrame:CGRectMake(0, 0, 100, 40)];

                    [self.viewaddSubview:label];

                    label.text = @"haha"

;

NSAttributedString *attrStr =

                    [[NSAttributedStringalloc]initWithString:label.text

attributes:

@{NSFontAttributeName:[UIFontsystemFontOfSize:20.f],

NSForegroundColorAttributeName:[UIColorcyanColor],

NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle|NSUnderlinePatternSolid),

NSStrikethroughColorAttributeName:[UIColorblackColor]}];

                    label.attributedText = attrStr;

效果就是這樣的 example2:

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

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

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

                    cell.textLabel.attributedText = attributeStr; 

哈哈哈(假日), 效果是這樣的