免费开源的iOS开发学习平台

UILabel详解:2-常用的UILabel使用场景

在项目开发中,对于UILabel的使用存在一种相对复杂的使用场景:一个UILabel中显示不同的颜色或不同的字体文字。我们可以使用 NSAttributedText 和 NSMutableAttributedText 类,并设置UILabel的attributedText来实现上述效果。

应用实例

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *label =  [[UILabel alloc]initWithFrame:CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width - 40, 30)];
    label.text = @"九九学院 -- www.99ios.com";
    label.backgroundColor = [UIColor lightGrayColor];
    label.textAlignment =  NSTextAlignmentCenter;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:label.text];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0,4)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30] range:NSMakeRange(0, 4)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(12, 5)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:25] range:NSMakeRange(12, 5)];
    label.attributedText = attributedString;
    [self.view addSubview:label];
}

运行效果:

示例代码

https://github.com/99ios/7.5.2