在nambu的消息显示中,消息有着许多的特殊属性,例如在链接处,需要显示颜色为蓝色,鼠标变为handpointingcursor。但是呢这只是局部,又不能全部设置为这样,于是,就需要我们的NSAttributedString 或 NSMutableAttributedString.
NSMutableAttributedString 中含有这样的一个方法, – (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange name 是指需要添加的属性的名字: NSString *NSFontAttributeName; NSString *NSParagraphStyleAttributeName; NSString *NSForegroundColorAttributeName;
...value 则是对应着不同的name,有着不同的value,比如: NSFontAttributeName-------Default Helvetica 12-point NSForegroundColorAttributeName-------blackColor
...range ,则是指我们需要添加属性的范围。 NSForegroundColorAttributeName, NSFontAttributeName, nil];
即黑色,Helvetica-Bold字体,13号大。
于是,在range的帮助下,我们就可以添加我们所需要的属性。
需要注意的是NSMutableAttributedString 有addAttributes 和 setAttributes 这两个方法。add是指在原有的基础上,继续添加;set是指去掉原来,只有新增的属性。
这样的随意改变属性,就有个潜在的问题了,如何准确的获得这个string的rect呢?不同的字体,不同的大小,会导致rect跟以前的有差距,这样的差距会让信息显示极其不正确。
- (NSRect)boundingRectWithSize:(NSSize)size options:(NSStringDrawingOptions)options
size,可以指定信息显示的宽度或高度,options则是显示的要求。
这样返回的rect,则是我们想要的rect。
例如在nambu的tableview里,它的每一行里,其实是个textfield,当resize tableview时,信息也会随着压缩,使得行数越来越多,那么这是,textfield则需要变换它的高度。
NSRect rect = [attributedMessageText boundingRectWithSize:NSMakeSize([textfield frame].size.width, 0)
options:NSStringDrawingUsesLineFragmentOrigin];
那么,rect.size.height 则是我们所需要的textfield的高度。
NibiruTech based in Chengdu, China. This city has just survived from the May 12. 2008 earthquake. NibiruTech provides a promotion price, and 5% of this promotion income would be donated to Red Cross China.
Great web development services, very cost effective, We are extremely satisfied!
-William Gersham Meharg
Executive of E-xact Transactions
NibiruTech is one of the pioneers to use Ruby on Rails in China.
-Mike Meng, Chief Editor of Programmer Magazine