平时生活和工作中的iOSiOS开发技术文章

NSAttributedString使用

2016-12-15  本文已影响3431人  玉米包谷

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

设置字体样式属性常量

NSString * const NSFontAttributeName; 

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSFontAttributeName 
                   value:[UIFont systemFontOfSize:30] 
                   range:NSMakeRange(0, 2)];
样式
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)];
样式
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)];
样式
NSString * const NSKernAttributeName; 

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:string];
[mAttribute addAttribute:NSKernAttributeName
                   value:@10
                   range:NSMakeRange(0, 10)];
样式
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
NSString * const NSUnderlineStyleAttributeName;

NSMutableAttributedString * mAttribute = [[NSMutableAttributedString alloc] initWithString:ligatureStr];
[mAttribute addAttribute:NSUnderlineStyleAttributeName
                   value:@(NSUnderlinePatternDot|NSUnderlineStyleSingle)
                   range:NSMakeRange(0, 10)];
下划线样式
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)];
阴影
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];
图文混编
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)];
除了第四种方式,其他的好像没有什么区别
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;
上一篇下一篇

猜你喜欢

热点阅读