NSAttributedString使用

iOS富文本字符串AttributedString詳解
iOS 中的 Attribute - 富文本文字--作者Ammar

設置字體樣式屬性常量

  • 設置字體類型(默認 Helvetica(Neue)12)
NSString * const NSFontAttributeName; 

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSFontAttributeName 
                   value:[UIFont systemFontOfSize:30] 
                   range:NSMakeRange(0, 2)];
樣式
  • 設置段落樣式(默認defaultParagraphStyle)
NSString * const NSParagraphStyleAttributeName;   

NSMutableParagraphStyle * mParagraphStyle = [[NSMutableParagraphStyle  alloc] init];
mParagraphStyle.headIndent = 30;                  // 除了首行,全部縮進
mParagraphStyle.firstLineHeadIndent = 10;         // 首行縮進
mParagraphStyle.lineSpacing = 20;                 // 行間距       

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSParagraphStyleAttributeName
                       value:mParagraphStyle
                       range:NSMakeRange(0, string.length)];
// NSParagraphStyle主要是用來獲取defaultParagraphStyle的默認段落樣式,不具有可操作性奏司。
// CoreText開發(fā)中主要使用的是NSMutableParagraphStyle
@property(NS_NONATOMIC_IOSONLY) CGFloat lineSpacing; // 行間距
@property(NS_NONATOMIC_IOSONLY) CGFloat paragraphSpacing; // 段間隙
@property(NS_NONATOMIC_IOSONLY) NSTextAlignment alignment; // 文本排列 (對齊方式)
@property(NS_NONATOMIC_IOSONLY) CGFloat firstLineHeadIndent; // 首行縮進
@property(NS_NONATOMIC_IOSONLY) CGFloat headIndent; // 整體縮進(首行除外)
@property(NS_NONATOMIC_IOSONLY) CGFloat tailIndent; // 整體縮進(末行除外)
@property(NS_NONATOMIC_IOSONLY) NSLineBreakMode lineBreakMode; // 換行模式
@property(NS_NONATOMIC_IOSONLY) CGFloat minimumLineHeight; // 最小行高
@property(NS_NONATOMIC_IOSONLY) CGFloat maximumLineHeight; // 最大行高
@property(NS_NONATOMIC_IOSONLY) NSWritingDirection baseWritingDirection; // 文本的書寫方向(方向有三個惹盼,從左到右,從右到做凳寺,從上到下)
@property(NS_NONATOMIC_IOSONLY) CGFloat lineHeightMultiple;  //行間距倍數(shù)
@property(NS_NONATOMIC_IOSONLY) CGFloat paragraphSpacingBefore; //段首行空白空
@property(NS_NONATOMIC_IOSONLY) float hyphenationFactor;  // 連字屬性 在iOS,唯一支持的值分別為0和1
@property(null_resettable, copy, NS_NONATOMIC_IOSONLY) NSArray<NSTextTab *> *tabStops NS_AVAILABLE(10_0, 7_0); // 制表符
@property(NS_NONATOMIC_IOSONLY) CGFloat defaultTabInterval NS_AVAILABLE(10_0, 7_0); 
@property(NS_NONATOMIC_IOSONLY) BOOL allowsDefaultTighteningForTruncation NS_AVAILABLE(10_11, 9_0);

- (void)addTabStop:(NSTextTab *)anObject NS_AVAILABLE(10_0, 9_0);
- (void)removeTabStop:(NSTextTab *)anObject NS_AVAILABLE(10_0, 9_0);

- (void)setParagraphStyle:(NSParagraphStyle *)obj NS_AVAILABLE(10_0, 9_0);
樣式
  • 設置字體顏色(默認黑色)
NSString * const NSForegroundColorAttributeName;

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSForegroundColorAttributeName
                     value:[UIColor redColor]
                     range:NSMakeRange(0, 10)];



樣式
  • 改變字體背景顏色(默認黑色)
NSString * const NSBackgroundColorAttributeName;

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSBackgroundColorAttributeName
                     value:[UIColor redColor]
                     range:NSMakeRange(0, 10)];
樣式
  • 連體字(該屬性所對應的值是一個 NSNumber 對象(整數(shù))彤侍。連體字符是指某些連在一起的字符肠缨,它們采用單個的圖元符號。0 表示沒有連體字符盏阶。1 表示使用默認的連體字符晒奕。2表示使用所有連體符號。默認值為 1(注意名斟,iOS 不支持值為 2)
NSString *const NSLigatureAttributeName;
[mAttribute addAttribute:NSLigatureAttributeName
                     value:[NSNumber numberWithInt: 0]
                     range:NSMakeRange(0, 10)];

// 由于要展示連體字符脑慧,所以字符串換成 flush
[mAttribute addAttribute:NSFontAttributeName
                     value:[UIFont fontWithName: @"futura" size: 30]
                     range:NSMakeRange(0, ligatureStr.length)];
樣式
  • 設置字與字之間的間距,默認為0(越大離得越遠 越小則越緊湊)
NSString * const NSKernAttributeName; 

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSKernAttributeName
                   value:@10
                   range:NSMakeRange(0, 10)];
樣式
  • 刪除線設置(默認0砰盐,無刪除線)
NSString * const NSStrikethroughStyleAttributeName;

[mAttribute addAttribute:NSStrikethroughStyleAttributeName
                     value:@(NSUnderlinePatternDot|NSUnderlineStyleSingle)
                     range:NSMakeRange(0, 10)];

線條的樣式的樣式闷袒,以下NSUnderlinePattern需要與NSUnderline交叉使用才有效果

typedef NS_ENUM(NSInteger, NSUnderlineStyle) {
    NSUnderlineStyleNone         = 0x00,   // 無樣式
    NSUnderlineStyleSingle       = 0x01,   // 下劃線(細)
    NSUnderlineStyleThick        = 0x02,   // 下劃線(粗)
    NSUnderlineStyleDouble       = 0x09,   // 雙下劃線
    NSUnderlinePatternSolid      = 0x0000, // 固體
    NSUnderlinePatternDot        = 0x0100, // 圓點
    NSUnderlinePatternDash       = 0x0200, // 破折號
    NSUnderlinePatternDashDot    = 0x0300, // 破折號圓點
    NSUnderlinePatternDashDotDot = 0x0400, // 破折號雙圓點
    NSUnderlineByWord            = 0x8000  // 詞
} NS_ENUM_AVAILABLE(10_0, 6_0);
NSUnderlineStyleSingle
NSUnderlineStyleThick
NSUnderlineStyleDouble
NSUnderlineStyleSingle|NSUnderlinePatternDot
  • 下劃線樣式屬性(注意:文字里添加非漢字的符號(如?)下劃線會向下移動,0無下劃線岩梳,樣式和上面相同)
NSString * const NSUnderlineStyleAttributeName;

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSUnderlineStyleAttributeName
                   value:@(NSUnderlinePatternDot|NSUnderlineStyleSingle)
                   range:NSMakeRange(0, 10)];
下劃線樣式
  • 以下兩個要配合使用囊骤,用于設置筆畫的顏色和寬度(默認為0,無效果)
NSString * const NSStrokeColorAttributeName;        
NSString * const NSStrokeWidthAttributeName;

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSStrokeColorAttributeName
                   value:[UIColor redColor]
                   range:NSMakeRange(0, 10)];
 [mAttribute addAttribute:NSStrokeWidthAttributeName
                    value:@(0.5)
                    range:NSMakeRange(0, 10)];
寬度為0.5時
寬度為10時
  • 設置陰影
NSString *const NSShadowAttributeName;

NSShadow * shadow = [[NSShadow alloc] init];
shadow.shadowBlurRadius = 2; // 模糊度
shadow.shadowColor = [UIColor purpleColor]; // 陰影顏色
shadow.shadowOffset = CGSizeMake(5, 10);     // 陰影偏移

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSShadowAttributeName 
                     value:shadow
                     range:NSMakeRange(0, 10)];
陰影
  • 文字特效打印效果 目前只能使用NSTextEffectLetterpressStyle
NSString *const NSTextEffectAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSTextEffectAttributeName
                     value:NSTextEffectLetterpressStyle
                     range:NSMakeRange(0, 10)];
仔細觀察冀值,會有種凹凸效果
  • 圖文混編
NSString *const NSAttachmentAttributeName;
// 初始化一個圖文對象
NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"image"];   // 設置圖片
attachment.bounds = CGRectMake(0, 0, 50, 50);       // 設置圖片大小
    
// 初始化一個NSAttributedString對象用于獲取圖文對象
NSAttributedString * attribute1 = [NSAttributedString attributedStringWithAttachment:attachment];
    
// 將新的NSAttibutedString對象插入舊的對象中
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute insertAttributedString:attribute1 atIndex:3];
圖文混編
  • 添加超鏈接(在UIlabel中無法點擊也物,但是在UITextView的協(xié)議方法中可以點擊)
NSString *const NSLinkAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSLinkAttributeName
                   value:[NSURL URLWithString:@"http://www.baidu.com"]
                   range:NSMakeRange(0, 10)];
超鏈接
  • 調整基線位置 從而改變字體初始位置(垂直方向,正數(shù)往上列疗,負數(shù)往下)
NSString *const NSBaselineOffsetAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSBaselineOffsetAttributeName
                   value:@10
                   range:NSMakeRange(0, 10)];
調整基線
  • 設置下劃線顏色
NSString *const NSUnderlineColorAttributeName;
[mAttribute addAttribute:NSUnderlineColorAttributeName
                   value:[UIColor redColor]
                   range:NSMakeRange(0, 10)];
[mAttribute addAttribute:NSUnderlineStyleAttributeName
                   value:@(NSUnderlinePatternDot|NSUnderlineStyleSingle)
                   range:NSMakeRange(0, 10)];
下劃線顏色
  • 設置刪除線顏色
NSString *const NSStrikethroughColorAttributeName;
[mAttribute addAttribute:NSStrikethroughColorAttributeName
                   value:[UIColor redColor]
                   range:NSMakeRange(0, 10)];
[mAttribute addAttribute:NSStrikethroughStyleAttributeName
                   value:@(NSUnderlinePatternDot|NSUnderlineStyleSingle)
                   range:NSMakeRange(0, 10)];
刪除線顏色
  • 字體書寫方向 有以下幾種組合
// 四種書寫方式
@[@(NSWritingDirectionLeftToRight | NSTextWritingDirectionEmbedding)]
@[@(NSWritingDirectionLeftToRight | NSTextWritingDirectionOverride)]
@[@(NSWritingDirectionRightToLeft | NSTextWritingDirectionEmbedding)]
@[@(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]

NSString *const NSWritingDirectionAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSWritingDirectionAttributeName
                   value:@[@(NSWritingDirectionLeftToRight | NSWritingDirectionEmbedding)]
                   range:NSMakeRange(0, ligatureStr.length)];
除了第四種方式滑蚯,其他的好像沒有什么區(qū)別
  • 文本方向(0水平、1垂直抵栈,目前在iOS,它總是水平告材。)
NSString *const NSVerticalGlyphFormAttributeName
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSVerticalGlyphFormAttributeName
                   value:@0
                   range:NSMakeRange(0, string.length)];
  • 設置字體傾斜(正向右傾斜 負向左傾斜)
NSString *const NSObliquenessAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string]; [mAttribute addAttribute:NSObliquenessAttributeName
                   value:@1
                   range:NSMakeRange(0, string.length)];
字體傾斜度
  • 設置字體壓縮、拉伸(正拉伸 負壓縮)
NSString *const NSExpansionAttributeName;
[mAttribute addAttribute:NSExpansionAttributeName
                   value:@-1
                   range:NSMakeRange(0, string.length)];
拉伸效果

壓縮效果
- (void)fixAttributesInRange:(NSRange)range;
@interface NSMutableAttributedString (NSAttributedStringAttributeFixing)
// 此方法修復范圍內的屬性不一致竭讳。
// 在調用該方法后创葡,它會將指定范圍內的字體屬性進行統(tǒng)一。
// 針對沒有進行字體屬性設置的范圍绢慢,如果范圍內有一段字體已經設置了屬性灿渴,則這段設置了屬性的字體不會發(fā)生變化洛波。
- (void)fixAttributesInRange:(NSRange)range NS_AVAILABLE(10_0, 7_0);
@end

// 使用
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:30]
                   range:NSMakeRange(0, 5)];
[mAttribute addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:20.0f]
                   range:NSMakeRange(5, 5)];
[mAttribute fixAttributesInRange:NSMakeRange(0, string.length)];

執(zhí)行前

執(zhí)行后

NSString * const NSPlainTextDocumentType;

// 展示純文本文檔類型的內容(例如txt),建議使用UITextView來展示
NSString * const NSPlainTextDocumentType;

// 創(chuàng)建從Bundle中來自TXT文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"txt"];
    
// 用TXT創(chuàng)建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:@{NSDocumentTypeDocumentAttribute:NSPlainTextDocumentType} documentAttributes:nil error:nil];
NSPlainTextDocumentType

NSString * const NSRTFTextDocumentType;

// 展示RTF文檔類型的內容,建議使用UITextView來展示
NSString * const NSRTFTextDocumentType;   
// 創(chuàng)建從Bundle中來自RTF文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"rtf"];
    
// 用RTF創(chuàng)建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSRTFTextDocumentType

NSString * const NSRTFDTextDocumentType;

// 展示RTFD文本文檔類型骚露,建議使用UITextView來展示
NSString * const NSRTFDTextDocumentType;   

// 創(chuàng)建從Bundle中來自RTFD文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"rtfd"];
    
// 用RTFD創(chuàng)建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:@{NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType} documentAttributes:nil error:nil];
NSRTFDTextDocumentType

NSString * const NSHTMLTextDocumentType;

// 展示HTML文本文檔類型的內容
NSString * const NSHTMLTextDocumentType;

// 第一類方法:
NSString *html = @"<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!";
NSData * data = [html dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];

// 第二類方法:
// 創(chuàng)建從Bundle中來自HTML文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"htm"];
// 用HTML創(chuàng)建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];

/* htm中的內容
<div style="background-color:#F1F1F1; font-size:14px; color:#304182;
    text-align:center; margin-left:10px; padding-right:10px">
    <p>iOS <span style="font-size:18px; color:#E88834;">Developer</span> Tips</p>
</div>
*/

NSPlainTextDocumentType--第一種
NSPlainTextDocumentType--第二種

NSString * const NSDocumentTypeDocumentAttribute

// 該鍵的值對應著以下四個(以上已有說明):
// NSString * const NSPlainTextDocumentType
// NSString * const NSRTFTextDocumentType
// NSString * const NSRTFDTextDocumentType
// NSString * const NSHTMLTextDocumentType
NSString * const NSDocumentTypeDocumentAttribute

富文本屬性


NSString * const NSTextLayoutSectionOrientation; // 文本布局方向
NSString * const NSTextLayoutSectionRange;// 文本布局范圍

// 純文本的文檔屬性
NSString * const NSCharacterEncodingDocumentAttribute; // 編碼格式

// 該例子是將一串HTML字符串編碼成UTF8蹬挤,再轉回NSAttributeString
NSString * htmlString =  @"<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!";
NSAttributedString *attributeString = [self htmlAttributeStringByHtmlString:htmlString];
NSString * string = [self htmlStringByHtmlAttributeString:attributeString];
attributeString = [self htmlAttributeStringByHtmlString:string];

// 將超文本格式化為富文本
- (NSAttributedString *)htmlAttributeStringByHtmlString:(NSString *)htmlString
{
    NSAttributedString *attributeString; 
    NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
    NSError *error = nil;
    attributeString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
    return attributeString;
}

// 將富文本格式化為超文本*/
- (NSString *)htmlStringByHtmlAttributeString:(NSAttributedString *)htmlAttributeString
{
    NSString *htmlString; NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
    NSData *htmlData = [htmlAttributeString dataFromRange:NSMakeRange(0, htmlAttributeString.length) documentAttributes:exportParams error:nil];
    htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
    return htmlString;
}

NSString * const NSDefaultAttributesDocumentAttribute; // 默認的富文本屬性

// RTF 和 RTFD 的文檔屬性
NSString * const NSPaperSizeDocumentAttribute; // 頁大小
NSString * const NSPaperMarginDocumentAttribute; // 頁邊距
NSString * const NSViewSizeDocumentAttribute; // 視圖大小
NSString * const NSViewZoomDocumentAttribute; // 縮放比例
NSString * const NSViewModeDocumentAttribute; // 頁面布局

// 文檔的設置
NSString * const NSReadOnlyDocumentAttribute; // 只讀屬性
NSString * const NSBackgroundColorDocumentAttribute; // 背景色
NSString * const NSHyphenationFactorDocumentAttribute; // 連字符號因素
NSString * const NSDefaultTabIntervalDocumentAttribute;// 當前停留在哪個選項卡
NSString * const NSTextLayoutSectionsAttribute;// 布局

// 以上屬性可以用過以下方式獲取
// 將dic1傳入documentAttributes,執(zhí)行完后可打印顯示其中的值
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"rtf"];
NSDictionary * dic1 = nil;
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:nil documentAttributes:&dic1 error:nil];
/**
  初始化NSAttributedString(9.0之后棄用)
  @param url     文檔路徑
  @param options 設置文檔屬性
  @param dict    用于獲取文檔屬性
  @param erro    錯誤內容
  @return NSAttributedString
*/
-(nullable instancetype)initWithURL:(NSURL *)url options:(NSDictionary<NSString *, id> *)options documentAttributes:(NSDictionary<NSString *, id> * __nullable * __nullable)dict error:(NSError **)error

/**
  初始化NSAttributedString
  @param data    某段字符串轉轉換的NSData(該字符串可以是html棘幸、rtf焰扳、rtfd、txt類型的)
  @param options 設置屬性
  @param dict    獲取文檔屬性
  @param error 錯誤
  @return NSAttributedString
*/
- (nullable instancetype)initWithData:(NSData *)data options:(NSDictionary<NSString *, id> *)options documentAttributes:(NSDictionary<NSString *, id> * __nullable * __nullable)dict error:(NSError **)error;

// 用法
NSString * htmlString = @"<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!";
NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
NSError *error = nil; 
NSAttributedString *attributeString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error]; 

/**
  初始化NSAttributedString(9.0之后棄用)
  @param url     文檔路徑
  @param options 設置文檔屬性
  @param dict    用于獲取文檔屬性
  @param erro    錯誤內容
  @return NSAttributedString
*/
- (nullable instancetype)initWithFileURL:(NSURL *)url options:(NSDictionary *)options documentAttributes:(NSDictionary* __nullable * __nullable)dict error:(NSError **)error

// 用法(可打印dict獲取其中的文檔屬性)
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"rtf"];
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:nil documentAttributes:&dict error:nil];

// 在接收到的內容范圍內生成一個NSData误续。
// 它要求文檔屬性字典中至少指定NSDocumentTypeDocumentAttribute來確定格式(7.0棄用)
- (nullable NSData *)dataFromRange:(NSRange)range documentAttributes:(NSDictionary<NSString *, id> *)dict error:(NSError **)error;

// 在內容范圍內返回NSFileWrapper對象吨悍。
// 它要求文檔屬性字典中至少指定NSDocumentTypeDocumentAttribute來確定格式。
// 該方法返回一個對應這些文件類型的文件包蹋嵌,如NSRTFDTextDocumentType表示目錄文件的包裝育瓜;
// 否則,它返回一個普通文件文件的包裝栽烂。
- (nullable NSFileWrapper *)fileWrapperFromRange:(NSRange)range documentAttributes:(NSDictionary<NSString *, id> *)dict error:(NSError **)error NS_AVAILABLE(10_0, 7_0);

/* 
    用外部文檔數(shù)據(jù)替換接收器內容的方法躏仇。
    options指定用于解釋文檔內容的文檔屬性,NSDocumentTypeDocumentAttribute腺办,NSCharacterEncodingDocumentAttribute和NSDefaultAttributesDocumentAttribute是受支持的選項鍵焰手。
    當沒有指定它們時,這些方法將檢查數(shù)據(jù)并且最好地檢測適當?shù)膶傩浴?    如果dict是非NULL怀喉,它將返回一個字典與各種文檔范圍的屬性可以通過NS ... DocumentAttribute鍵訪問书妻。
*/

// 9.0之后棄用,通過一個文檔的URL地址讀取文檔的內容躬拢,如果不存在會返回NO
- (BOOL)readFromURL:(NSURL *)url options:(NSDictionary<NSString *, id> *)opts documentAttributes:(NSDictionary<NSString *, id> * __nullable * __nullable)dict error:(NSError **)error;

// 用法(此為例子驻子,并非唯一用法):
NSDictionary * dic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
NSDictionary * dic1 = nil;
NSURL * URL = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"rtf"];
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithURL:URL options:dic documentAttributes:&dic1 error:nil];
NSLog(@"%d",[mAttribute readFromURL:URL options:dic documentAttributes:&dic1 error:nil]);

// 7.0之后棄用,通過一個文檔的URL地址讀取文檔的內容估灿,如果不存在會返回NO
- (BOOL)readFromData:(NSData *)data options:(NSDictionary<NSString *, id> *)opts documentAttributes:(NSDictionary<NSString *, id> * __nullable * __nullable)dict error:(NSError **)error NS_AVAILABLE(10_0, 7_0);

// 用法(此為例子,并非唯一用法):
NSURL * URL = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"rtf"];
NSData * data = [[NSData alloc] initWithContentsOfURL:URL];
NSDictionary * dic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
NSDictionary * dic1 = nil;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithData:data options:dic documentAttributes:&dic1 error:nil];
NSLog(@"%d",[mAttribute readFromData:data options:dic1 documentAttributes:&dic1 error:nil]);
// 獲取NSAttributeString中的字符長度
@property (readonly) NSUInteger length;

// 獲取一個NSAttributeString中某個位置的字符屬性
- (nullable id)attribute:(NSString *)attrName atIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range;
  NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
  [mAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, 1)];
  [mAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3, 1)];
  id object = [mAttribute attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:nil];

// 截取一個NSAttributeString指定范圍內的NSAttributeString并返回
- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range;

/**
  獲取某個位置的字符屬性缤剧,以字典的形式返回
  并且它通過傳入rangeLimit來限制這個方法的范圍
  如果傳入range馅袁,可以獲取這個字符屬性的最大有效范圍

  @param location   指定的位置
  @param range      最大的有效范圍,申明一個NSRange荒辕,以&NSRange的形式傳入方法
  @param rangeLimit 限制范圍
  @return 指定位置所有字符屬性
*/
- (NSDictionary<NSString *, id> *)attributesAtIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit;
    
    
/**
  通過一個字符屬性key(如NSFontAttributeName)和一個指定位置來獲取它在一整個NSAttributeString中的最大有效范圍和該字符屬性的詳情

  @param attrName   字符屬性key
  @param location   指定位置
  @param range      最大有效范圍
  @param rangeLimit 限制范圍(方法對NSAttributeString的作用范圍)
  @return 屬性詳情
*/
- (nullable id)attribute:(NSString *)attrName atIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit
    
/**
判斷兩個NSAttributeString是否一致(任何一項不同都會返回NO)

  @param other 另一個NSAttributeString
  @return 比較結果
*/
- (BOOL)isEqualToAttributedString:(NSAttributedString *)other;
    
/**
  初始化
*/
- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs;
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
    
/**
  一些方法的搜索方向
*/
  - NSAttributedStringEnumerationReverse: 逆向搜索
  - NSAttributedStringEnumerationLongestEffectiveRangeNotRequired: 順向搜索
*/
  typedef NS_OPTIONS(NSUInteger, NSAttributedStringEnumerationOptions) {
  NSAttributedStringEnumerationReverse汗销,
  NSAttributedStringEnumerationLongestEffectiveRangeNotRequire
  };
    
/**
  遍歷NSAttributeString,返回詳細字符屬性和它的有效范圍

  @param enumerationRange 遍歷的范圍
  @param opts 枚舉
  @param block 循環(huán)回調返回信息抵窒,循環(huán)次數(shù)是一段字符串中所有不同的Attribute的個數(shù)
*/
- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(NSDictionary<NSString *, id> *attrs, NSRange range, BOOL *stop))block;
  NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
  [mAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, 2)];
  [mAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0f] range:NSMakeRange(0, 3)];
  [mAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(2, 4)];
  [mAttribute enumerateAttributesInRange:NSMakeRange(0, string.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        NSLog(@"attrs = %@ range = %@ stop = %d",attrs,NSStringFromRange(range),*stop);
  }];
   
/**
  遍歷NSAttributeString弛针,返回指定屬性字段的值和有效范圍
     
  @param attrName         屬性字段
  @param enumerationRange 遍歷的范圍
  @param opts 枚舉
  @param block 回調返回信息
*/
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(id _Nullable value, NSRange range, BOOL *stop))block;
  NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
  [mAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, 2)];
  [mAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0f] range:NSMakeRange(0, 3)];
  [mAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(2, 4)];
  [mAttribute enumerateAttribute:NSForegroundColorAttributeName inRange:NSMakeRange(0, string.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        NSLog(@"value = %@ range = %@ stop = %d",value,NSStringFromRange(range),*stop);
  }];

// 控制臺打印如下
value = UIExtendedSRGBColorSpace 1 1 0 1 range = {0, 2} stop = 0
value = UIExtendedSRGBColorSpace 1 0.5 0 1 range = {2, 1} stop = 0
value = UIExtendedSRGBColorSpace 1 0.5 0 1 range = {3, 3} stop = 0
value = (null) range = {6, 3} stop = 0

/**
 將NSMutableAttribute指定范圍內的字符替代

 @param range 替代范圍
 @param str   替代后的字符
 */
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;

/**
 設置范圍內的字符屬性

 @param attrs 字符屬性
 @param range 設置范圍
 */
- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市李皇,隨后出現(xiàn)的幾起案子削茁,更是在濱河造成了極大的恐慌宙枷,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件茧跋,死亡現(xiàn)場離奇詭異慰丛,居然都是意外死亡,警方通過查閱死者的電腦和手機瘾杭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門诅病,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人粥烁,你說我怎么就攤上這事贤笆。” “怎么了讨阻?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵芥永,是天一觀的道長。 經常有香客問我变勇,道長恤左,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任搀绣,我火速辦了婚禮飞袋,結果婚禮上,老公的妹妹穿的比我還像新娘链患。我一直安慰自己巧鸭,他們只是感情好,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布麻捻。 她就那樣靜靜地躺著纲仍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪贸毕。 梳的紋絲不亂的頭發(fā)上郑叠,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機與錄音明棍,去河邊找鬼乡革。 笑死,一個胖子當著我的面吹牛摊腋,可吹牛的內容都是我干的沸版。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼兴蒸,長吁一口氣:“原來是場噩夢啊……” “哼视粮!你這毒婦竟也來了?” 一聲冷哼從身側響起橙凳,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤蕾殴,失蹤者是張志新(化名)和其女友劉穎笑撞,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體区宇,經...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡娃殖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了议谷。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片炉爆。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖卧晓,靈堂內的尸體忽然破棺而出芬首,到底是詐尸還是另有隱情,我是刑警寧澤逼裆,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布郁稍,位于F島的核電站,受9級特大地震影響胜宇,放射性物質發(fā)生泄漏耀怜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一桐愉、第九天 我趴在偏房一處隱蔽的房頂上張望财破。 院中可真熱鬧,春花似錦从诲、人聲如沸左痢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽俊性。三九已至,卻和暖如春描扯,著一層夾襖步出監(jiān)牢的瞬間定页,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工绽诚, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留拯勉,地道東北人。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓憔购,卻偏偏與公主長得像,于是被迫代替她去往敵國和親岔帽。 傳聞我的和親對象是個殘疾皇子玫鸟,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內容