属性字符串(NSAttributedString)的简单应用

属性字符串NSAttributedString 可以对字符串附加格式信息,由于对于对不同文本片段使用不同的格式,属性字符串类特别合适。

IOS 6中对样式文本有了大改善,大部分主要的UIKit控件都允许使用属性字符串。举例UILable,只要创建一个属性字符串,然后赋值给标签的attributedText属性即可。

- (IBAction)buttonPressed:(UIButton *)sender {
    //按钮标题
    NSString *title = [sender titleForState:UIControlStateNormal];
    //标签标题
    NSString *plainTitle = [NSString stringWithFormat:@"%@ button press", title];
//    _statusLabel.text = plainTitle;
    
    //创建属性字符串对象
    NSMutableAttributedString *styledText = [[NSMutableAttributedString alloc] initWithString:plainTitle];
    
    //修改属性字符串中的某文件的字体(加粗)
    NSDictionary *attributes =
    @{
      NSFontAttributeName : [UIFont boldSystemFontOfSize:_statusLabel.font.pointSize]
      };
    NSRange rang = [plainTitle rangeOfString:title];
    [styledText setAttributes:attributes range:rang];
    
    //赋值给标签
    _statusLabel.attributedText = styledText;
}

 

效果如下:

Left button press

 

posted @ 2016-03-20 11:37  smile_smile  阅读(360)  评论(0编辑  收藏  举报