2.30 Constructing and Displaying Styled Texts

来源:互联网 发布:苏享茂 知乎 编辑:程序博客网 时间:2024/05/17 22:18

想象一下,一个UILabel上的一段文本有两个字比较重要,老板说这两个字要加粗,还有另外两个字要提示下,要加下划线。该怎么做呢?
很简单吗,分成几个Label来显示不就行了。你说对了,但一旦文本内容稍微有点变化,你可能就要调整各个label的位置了。有没有更好的办法呢?IOS提供了NSAttributedString来解决这类事情,它只需要一个label就可以把这些全搞定。天啊,他是怎么做到的。我也不知道他是怎么做到的,不过我们先来知道下怎么用。对了,他可不仅仅能用在label上哦。

富文本从来就是个很传奇的东西,可能你会想用WebView来显示富文本。一则比较慢,二则他展示的效果可能不是你想要的。最后,从ios6开始,我们可以使用attributed strings。据说这在mac上早就有了。

假设我们想显示文本“IOS SDK”
"IOS"部分显示要求
1,加粗 60号
2,背景黑色
3,前景红色
"SDK"部分显示要求
1,加粗 60号
2,白色文本
3,灰色阴影

--书上代码如下--

- (NSAttributedString *) attributedText{
NSString *string = @"iOS SDK";
NSMutableAttributedString *result = [[NSMutableAttributedString alloc]
initWithString:string];
NSDictionary *attributesForFirstWord = @{
NSFontAttributeName : [UIFont boldSystemFontOfSize:60.0f],
NSForegroundColorAttributeName : [UIColor redColor],
NSBackgroundColorAttributeName : [UIColor blackColor]
};
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor darkGrayColor];
shadow.shadowOffset = CGSizeMake(4.0f, 4.0f);
NSDictionary *attributesForSecondWord = @{
NSFontAttributeName : [UIFont boldSystemFontOfSize:60.0f],
NSForegroundColorAttributeName : [UIColor whiteColor],
NSBackgroundColorAttributeName : [UIColor redColor],
NSShadowAttributeName : shadow
};
/* Find the string "iOS" in the whole string and sets its attribute */
[result setAttributes:attributesForFirstWord
range:[string rangeOfString:@"iOS"]];
/* Do the same thing for the string "SDK" */
[result setAttributes:attributesForSecondWord
range:[string rangeOfString:@"SDK"]];
return [[NSAttributedString alloc] initWithAttributedString:result];

}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.label = [[UILabel alloc] init];
self.label.backgroundColor = [UIColor clearColor];
self.label.attributedText = [self attributedText];
[self.label sizeToFit];
self.label.center = self.view.center;
[self.view addSubview:self.label];
}
@end

我们来看看NSMutableAttributedString 的setAttributes: range: 方法
Attributes参数是个NSDictionary类,在dictionary里面指定文本显示的字体大小,颜色,背景色等。rang用来指定对哪些字符应用这套dictionary方案。

 

 

 

 

 

 

 

 


 

原创粉丝点击