iOS在一个label中显示不同颜色的字体

时间:2022-11-08 14:37:31

UILabel *Label = [[UILabel alloc] initWithFrame:CGRectMake(20, 300, 300, 30)];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"set background color with button"];

[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,2)];

[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];

[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];

[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:17.0] range:NSMakeRange(0, 5)];

[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:17.0] range:NSMakeRange(6, 12)];

[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:17.0] range:NSMakeRange(19, 6)];

Label.attributedText = string;

[self.view addSubview:Label];

   效果图 :  set background color with button