iOS:NSAttributedString

NSAttributedString管理一个字符串,以及与该字符串中的单个字符或某些范围的字符串相关的属性。NSAttributedString就是用来存储一串文字以及文字的诸如大小、颜色、字体等attribute的带属性的字符串,具体实现时,NSAttributedString维护了一个NSString,用来保存最原始的字符串,另有一个NSDictionary用来保存各个子串/字符的属性。

创建 Attributed String

有3种方法创建Attributed String。

1. 使用initWithString:, initWithString:attributes:, 或者 initWithAttributedString: ,下面是一个实例代码:

NSFont *font = [NSFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                    forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil"
            attributes:attrsDictionary];

 可以看到上面创建的整个字符串关联了Font属性。如果希望只是对某一范围的字符串施加某个属性应该使用NSMutableAttributedString的 setAttributes:range:方法。这里例子是使用了Font属性,在Appkit中特殊定义了若干属性,这些属性被用于Core Text中。其他的属性包括前景色、背景色、是否有shadow等,具体可见本文

2. 使用initWithRTF:documentAttributes:, initWithRTFD:documentAttributes:, and initWithRTFDFileWrapper:documentAttributes:从rich text (RTF) 或者 rich text with attachments (RTFD) 数据中创建。

NSData *rtfData = ...;  // assume rtfData is an NSData object containing valid RTF data
NSDictionary *docAttributes;
NSSize paperSize;
 
NSAttributedString *attrString;
 
if ((attrString = [[NSAttributedString alloc]
        initWithRTF: rtfData documentAttributes: &docAttributes])) {
 
    NSValue *value = [docAttrs objectForKey:@"PaperSize"];
    paperSize = [value sizeValue];
    // implementation continues...

3. 使用initWithHTML:documentAttributes: 和 initWithHTML:baseURL:documentAttributes:从HTML数据中创建。有线程安全问题,使用时需要注意。

对RTF和HTML的支持都是AppKit对NSAttributedString的扩展。

Accessing Attributes

从上面对这个类的介绍可以知道,如果我们要访问某个子串/字符的属性,需要提供子串的位置和属性的名字,而如果不提供属性名字,那就把所有属性都返回。下面就是其对应的APIs:

attributesAtIndex:effectiveRange:
attributesAtIndex:longestEffectiveRange:inRange:
attribute:atIndex:effectiveRange:
attribute:atIndex:longestEffectiveRange:inRange:
fontAttributesInRange:
rulerAttributesInRange:

 fontAttributesInRange: 和 rulerAttributesInRange: 是由AppKit扩展的属性。

修改 Attributed String

NSMutableAttributedString提供若干方法,即可以修改字符串,又可以修改字符串的属性。经过多次修改后,有些信息可能变的不一致了,为了让信息保持一致,可以使用下面的方法:

fixAttributesInRange:
fixAttachmentAttributeInRange:
fixFontAttributeInRange:
fixParagraphStyleAttributeInRange:
beginEditing
endEditing

这些方法都是AppKit的扩展功能。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。