Introduction to Attributed Strings for iOS--WWDC 2012 session 222

这是样式化的字符串,在过去很少用到,但是当UILabel等UIKit原生支持这个之后,可以说对于开发节省了不少时间和心思。

 

对于上面这种的展示方式,在之前可能挠破头都很难去实现,但是现在可以用一个UILabel+NSAttributedString就轻松解决了。

 

最简单的初始化方式

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@”Dentist at 9:15am.” attributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:12.0f}];

添加新的样式

[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(11,6)];//Changethetime,9:15am,tored

效果就如下了

 

不过个人比较推崇NSMutableAttributedString,将不同样式的部分一个一个append,省去计算NSRange的麻烦。

 

下面列出的是iOS6下支持的attribute

Font           NSFontAttributeName (UIFont)

Text color       NSForegroundColorAttributeName (UIColor)

Paragraph style     NSParagraphStyleAttributeName (NSParagraphStyle)

Line break mode  与UILineBreakMode相似,在上面那个属性NSParagraphStyle(@property NSLineBreakMode lineBreakMode;)里面设置

Alignment      同样是在NSParagraphStyle(@property NSTextAlignment alignment;)里面设置

Text background color Ligature, kerning, and baseline offset

Underline and strike-through

Stroke width and color

Shadow

……详见SDK吧

 

对于UIKit的扩展,才发现有一两个有意思的:

1.setAttributedTitle:forControlState:,这是UIButton里面的,可以设置点击时候按钮标题的样式

2.pickerView:attributedTitleForRow:forComponent:,这是UIPickerView里面的,同样可以设置每一行显示内容的样式

 

总结一下,毕竟目前不需要支持iOS6.0以下的系统了,所以在以后的开发中尽可能使用AttributedString与UIKit结合,这样既省事又省心。

或许在我看到WWDC2013的时候,会增加些iOS7的东西,再说吧。

posted @ 2014-05-12 14:50  卓毅  阅读(399)  评论(0编辑  收藏  举报