iOS NSMuttableAttstring~詳解

//聯系人:石虎QQ: 1224614774昵稱:嗡嘛呢叭咪哄

一、NSMuttableAttstring實例化方法

1.實例化方法:

使用字符串初始化

- (id)initWithString:(NSString?*)str;

- (id)initWithString:(NSString?*)str attributes:(NSDictionary?*)attrs;

2.字典中存放一些屬性名和屬性值,如:

NSDictionary?*attributeDict = [NSDictionarydictionaryWithObjectsAndKeys:

[UIFontsystemFontOfSize:15.0],NSFontAttributeName,

[UIColorredColor],NSForegroundColorAttributeName,

NSUnderlineStyleAttributeName,NSUnderlineStyleSingle,nil];

NSMutableAttributedString*AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"今天我很帥"attributes:attributeDict];

- (id)initWithAttributedString:(NSAttributedString?*)attester;

注意:使用NSAttributedString初始化,跟NSMutableString,NSString類似

二、NSMuttableAttstring使用方法

1.使用方法

為某一范圍內文字設置多個屬性

- (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陰影

更多方法和屬性說明詳見蘋果官方說明文檔:點擊打開鏈接

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003689

3.使用實例:

//描述設置行距

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];[paragraphStyle setLineSpacing:4.0f];

//設置字體

NSDictionary*deitalAttributes =@{NSFontAttributeName :lbl_fetusDesc.font,

NSParagraphStyleAttributeName: paragraphStyle};

NSString*descStr = (self.topViewType == PregnantTopViewTypePregnant) ? _pregInfo.personateFetusAdviceDesc? : _pregInfo.bbchange;

NSMutableAttributedString*attributedString = [[NSMutableAttributedStringalloc]initWithString:descStr];

[attributedString addAttributes:deitalAttributes range:NSMakeRange(0, [descStr length])];

謝謝!!!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容