如果你不使用 NSAttributeLabel 然后
试试这个,它对我来说很好
将此方法添加到 CommonFuction 类中并添加此框架CoreText.framework
+ (void)setMultiColorAndFontText:(NSString *)text rangeString:(NSArray *)rangeString label:(UILabel*) label font:(NSArray*) fontName color:(NSArray*) colorName
{
label.layer.sublayers = nil;
NSMutableAttributedString *mutableAttributedString = [[ NSMutableAttributedString alloc]initWithString:text];
for (int i =0 ; i<[rangeString count]; i++)
{
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) [UIFont fontWithName:[fontName objectAtIndex:i] size:10.0].fontName, [UIFont fontWithName:[fontName objectAtIndex:i] size:10.0].pointSize, NULL);
NSRange whiteRange = [text rangeOfString:[rangeString objectAtIndex:i]];
if (whiteRange.location != NSNotFound)
{
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[colorName objectAtIndex:i] range:whiteRange];
[mutableAttributedString addAttribute:(NSString*)kCTFontAttributeName
value:( __bridge id)ctFont
range:whiteRange];
}
}
CGSize expectedLabelSize = [text sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:10.0f] constrainedToSize:CGSizeMake(186,100) lineBreakMode:UILineBreakModeWordWrap];
CATextLayer *textLayer = [[CATextLayer alloc]init];
textLayer.frame =CGRectMake(0,0, label.frame.size.width,expectedLabelSize.height+4);
textLayer.contentsScale = [[UIScreen mainScreen] scale];
textLayer.string=mutableAttributedString;
textLayer.opacity = 1.0;
textLayer.alignmentMode = kCAAlignmentLeft;
[label.layer addSublayer:textLayer];
[textLayer setWrapped:TRUE];
//label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"";
}
并在调用此方法后如下:-
[CommonFunctions setMultiColorAndFontText:string rangeString:[NSArray arrayWithObjects:str1,str2,str3,str4,str5,str6, nil] label:yourLabel font:[NSArray arrayWithObjects:@"Arial",@"Arial",@"Arial",@"Arial",@"Arial",@"Arial"nil] color:[NSArray arrayWithObjects:(UIColor *)[UIColor colorWithRed:(0/255.f) green:(167/255.f) blue:(230/255.f) alpha:1.0f].CGColor,(UIColor *)[UIColor colorWithRed:(189/255.f) green:(189/255.f) blue:(189/255.f) alpha:1.0f].CGColor, color3,color4,color5,color6,nil]];