NSAttributedString使用

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

設(shè)置字體樣式屬性常量

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

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

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

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSParagraphStyleAttributeName
                       value:mParagraphStyle
                       range:NSMakeRange(0, string.length)];
// NSParagraphStyle主要是用來獲取defaultParagraphStyle的默認(rèn)段落樣式,不具有可操作性。
// 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; // 首行縮進(jìn)
@property(NS_NONATOMIC_IOSONLY) CGFloat headIndent; // 整體縮進(jìn)(首行除外)
@property(NS_NONATOMIC_IOSONLY) CGFloat tailIndent; // 整體縮進(jìn)(末行除外)
@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);
樣式
  • 設(shè)置字體顏色(默認(rèn)黑色)
NSString * const NSForegroundColorAttributeName;

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



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

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSBackgroundColorAttributeName
                     value:[UIColor redColor]
                     range:NSMakeRange(0, 10)];
樣式
  • 連體字(該屬性所對應(yīng)的值是一個 NSNumber 對象(整數(shù))。連體字符是指某些連在一起的字符,它們采用單個的圖元符號。0 表示沒有連體字符。1 表示使用默認(rèn)的連體字符。2表示使用所有連體符號。默認(rèn)值為 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)];
樣式
  • 設(shè)置字與字之間的間距,默認(rèn)為0(越大離得越遠(yuǎn) 越小則越緊湊)
NSString * const NSKernAttributeName; 

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSKernAttributeName
                   value:@10
                   range:NSMakeRange(0, 10)];
樣式
  • 刪除線設(shè)置(默認(rèn)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,   // 下劃線(細(xì))
    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)];
下劃線樣式
  • 以下兩個要配合使用,用于設(shè)置筆畫的顏色和寬度(默認(rèn)為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時
  • 設(shè)置陰影
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)];
仔細(xì)觀察,會有種凹凸效果
  • 圖文混編
NSString *const NSAttachmentAttributeName;
// 初始化一個圖文對象
NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"image"];   // 設(shè)置圖片
attachment.bounds = CGRectMake(0, 0, 50, 50);       // 設(shè)置圖片大小
    
// 初始化一個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)];
超鏈接
  • 調(diào)整基線位置 從而改變字體初始位置(垂直方向,正數(shù)往上,負(fù)數(shù)往下)
NSString *const NSBaselineOffsetAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSBaselineOffsetAttributeName
                   value:@10
                   range:NSMakeRange(0, 10)];
調(diào)整基線
  • 設(shè)置下劃線顏色
NSString *const NSUnderlineColorAttributeName;
[mAttribute addAttribute:NSUnderlineColorAttributeName
                   value:[UIColor redColor]
                   range:NSMakeRange(0, 10)];
[mAttribute addAttribute:NSUnderlineStyleAttributeName
                   value:@(NSUnderlinePatternDot|NSUnderlineStyleSingle)
                   range:NSMakeRange(0, 10)];
下劃線顏色
  • 設(shè)置刪除線顏色
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)];
  • 設(shè)置字體傾斜(正向右傾斜 負(fù)向左傾斜)
NSString *const NSObliquenessAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string]; [mAttribute addAttribute:NSObliquenessAttributeName
                   value:@1
                   range:NSMakeRange(0, string.length)];
字體傾斜度
  • 設(shè)置字體壓縮、拉伸(正拉伸 負(fù)壓縮)
NSString *const NSExpansionAttributeName;
[mAttribute addAttribute:NSExpansionAttributeName
                   value:@-1
                   range:NSMakeRange(0, string.length)];
拉伸效果

壓縮效果
- (void)fixAttributesInRange:(NSRange)range;
@interface NSMutableAttributedString (NSAttributedStringAttributeFixing)
// 此方法修復(fù)范圍內(nèi)的屬性不一致。
// 在調(diào)用該方法后,它會將指定范圍內(nèi)的字體屬性進(jìn)行統(tǒng)一。
// 針對沒有進(jìn)行字體屬性設(shè)置的范圍,如果范圍內(nèi)有一段字體已經(jīng)設(shè)置了屬性,則這段設(shè)置了屬性的字體不會發(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;

// 展示純文本文檔類型的內(nèi)容(例如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文檔類型的內(nèi)容,建議使用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文本文檔類型的內(nèi)容
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中的內(nèi)容
<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

// 該鍵的值對應(yīng)著以下四個(以上已有說明):
// 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,再轉(zhuǎn)回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; // 默認(rèn)的富文本屬性

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

// 文檔的設(shè)置
NSString * const NSReadOnlyDocumentAttribute; // 只讀屬性
NSString * const NSBackgroundColorDocumentAttribute; // 背景色
NSString * const NSHyphenationFactorDocumentAttribute; // 連字符號因素
NSString * const NSDefaultTabIntervalDocumentAttribute;// 當(dāng)前停留在哪個選項卡
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 設(shè)置文檔屬性
  @param dict    用于獲取文檔屬性
  @param erro    錯誤內(nèi)容
  @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    某段字符串轉(zhuǎn)轉(zhuǎn)換的NSData(該字符串可以是html、rtf、rtfd、txt類型的)
  @param options 設(shè)置屬性
  @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 設(shè)置文檔屬性
  @param dict    用于獲取文檔屬性
  @param erro    錯誤內(nèi)容
  @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];

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

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

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

// 9.0之后棄用,通過一個文檔的URL地址讀取文檔的內(nèi)容,如果不存在會返回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地址讀取文檔的內(nèi)容,如果不存在會返回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指定范圍內(nèi)的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 比較結(jié)果
*/
- (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,返回詳細(xì)字符屬性和它的有效范圍

  @param enumerationRange 遍歷的范圍
  @param opts 枚舉
  @param block 循環(huán)回調(diào)返回信息,循環(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 回調(diào)返回信息
*/
- (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指定范圍內(nèi)的字符替代

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

/**
 設(shè)置范圍內(nèi)的字符屬性

 @param attrs 字符屬性
 @param range 設(shè)置范圍
 */
- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容