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开发中主要使用的是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;  //行间距倍数
@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 对象(整数)。连体字符是指某些连在一起的字符,它们采用单个的图元符号。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的协议方法中可以点击)
NSString *const NSLinkAttributeName;
NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSLinkAttributeName
                   value:[NSURL URLWithString:@"http://www.baidu.com"]
                   range:NSMakeRange(0, 10)];
超链接
  • 调整基线位置 从而改变字体初始位置(垂直方向,正数往上,负数往下)
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)];
除了第四种方式,其他的好像没有什么区别
  • 文本方向(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)
// 此方法修复范围内的属性不一致。
// 在调用该方法后,它会将指定范围内的字体属性进行统一。
// 针对没有进行字体属性设置的范围,如果范围内有一段字体已经设置了属性,则这段设置了属性的字体不会发生变化。
- (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)];

执行前

执行后

NSString * const NSPlainTextDocumentType;

// 展示纯文本文档类型的内容(例如txt),建议使用UITextView来展示
NSString * const NSPlainTextDocumentType;

// 创建从Bundle中来自TXT文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"txt"];
    
// 用TXT创建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:@{NSDocumentTypeDocumentAttribute:NSPlainTextDocumentType} documentAttributes:nil error:nil];
NSPlainTextDocumentType

NSString * const NSRTFTextDocumentType;

// 展示RTF文档类型的内容,建议使用UITextView来展示
NSString * const NSRTFTextDocumentType;   
// 创建从Bundle中来自RTF文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"rtf"];
    
// 用RTF创建attributed String
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html1 options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSRTFTextDocumentType

NSString * const NSRTFDTextDocumentType;

// 展示RTFD文本文档类型,建议使用UITextView来展示
NSString * const NSRTFDTextDocumentType;   

// 创建从Bundle中来自RTFD文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"rtfd"];
    
// 用RTFD创建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];

// 第二类方法:
// 创建从Bundle中来自HTML文件的URL
NSURL *html1 = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"htm"];
// 用HTML创建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,执行完后可打印显示其中的值
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);

/* 
    用外部文档数据替换接收器内容的方法。
    options指定用于解释文档内容的文档属性,NSDocumentTypeDocumentAttribute,NSCharacterEncodingDocumentAttribute和NSDefaultAttributesDocumentAttribute是受支持的选项键。
    当没有指定它们时,这些方法将检查数据并且最好地检测适当的属性。
    如果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 循环回调返回信息,循环次数是一段字符串中所有不同的Attribute的个数
*/
- (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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容