有时可能会遇到这样的问题,一个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];