`
king_tt
  • 浏览: 2115306 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

【移动开发】样式文本_NSMutableAttributedString

 
阅读更多

有时可能会遇到这样的问题,一个label中设置的文本含有2种以上不同的格式,又不能把它拆解为两个label来显示,这时用NSMutableAttributedString可以很好的解决问题。

- (IBAction)buttonPressed:(UIButton *)sender {
    NSString *title = [sender titleForState:UIControlStateNormal];
    NSString *plainText = [NSString stringWithFormat:@"%@ button pressed.", title];
//    statusLabel.text = plainText;

    NSMutableAttributedString *styledText = [[NSMutableAttributedString alloc]
                                             initWithString:plainText];
    
    NSDictionary *attributes = @{
    NSFontAttributeName : [UIFont boldSystemFontOfSize:statusLabel.font.pointSize]
    };

    NSRange nameRange = [plainText rangeOfString:title];
    
    [styledText setAttributes:attributes
                        range:nameRange];
    statusLabel.attributedText = styledText;
}

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
                                       initWithAttributedString: label.attributedText];
    [text addAttribute: NSForegroundColorAttributeName value:[UIColor redColor]
                 range: NSMakeRange(10, 1)];
    [label setAttributedText: text];

官方指南

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics