码迷,mamicode.com
首页 > 移动开发 > 详细

iOS:NSAttributedString

时间:2014-10-27 12:20:16      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   使用   for   

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的扩展功能。

iOS:NSAttributedString

标签:style   blog   http   color   io   os   ar   使用   for   

原文地址:http://www.cnblogs.com/LJson/p/4053711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!