您可以使用此类方法在控件(UILabel、UITextField 或 UItextView)中使用不同的颜色、不同的字体和不同大小的文本
+ (void)setMultiColorAndFontText:(NSString *)text rangeString:(NSArray *)rangeString inputView:(UITextView*) inputView font:(NSArray*) fontName color:(NSArray*) colorName
{
inputView.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:14.0].fontName, [UIFont fontWithName:[fontName objectAtIndex:i] size:14.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 expectedinputViewSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14.0f] constrainedToSize:CGSizeMake(186,100) lineBreakMode:UILineBreakModeWordWrap];
CATextLayer *textLayer = [[CATextLayer alloc]init];
textLayer.frame =CGRectMake(0,4, inputView.frame.size.width,expectedinputViewSize.height+4);
textLayer.contentsScale = [[UIScreen mainScreen] scale];
textLayer.string=mutableAttributedString;
textLayer.opacity = 1.0;
textLayer.alignmentMode = kCAAlignmentLeft;
[inputView.layer addSublayer:textLayer];
[textLayer setWrapped:TRUE];
[inputView setText:@""];
}
在这里你可以传递你的 text ,它的 range , font 和 color 作为参数。例子 :
[CommonFunctions setMultiColorAndFontText:@"This is a textview" rangeString:[NSArray arrayWithObjects:@"This is a",@"textview", nil] textfield:txtEmailAddress font:[NSArray arrayWithObjects:@"Arial",@"Helvetica",nil] color:[NSArray arrayWithObjects:(UIColor *)[UIColor whiteColor].CGColor,(UIColor *)[UIColor redColor].CGColor,nil]];
它将显示不同颜色和不同字体的文本。
注意:在这个方法中,我们使用了 UITextView。如果你需要 UILabel 或 UITextField 那么你只需要以同样的方式改变它:
UIL标签
+ (void)setMultiColorAndFontText:(NSString *)text rangeString:(NSArray *)rangeString inputView:(UILabel*) label font:(NSArray*) fontName color:(NSArray*) colorName;
UITextField
+ (void)setMultiColorAndFontText:(NSString *)text rangeString:(NSArray *)rangeString inputView:(UITextField*) label font:(NSArray*) fontName color:(NSArray*) colorName;
UITextView
+ (void)setMultiColorAndFontText:(NSString *)text rangeString:(NSArray *)rangeString inputView:(UITextView*) label font:(NSArray*) fontName color:(NSArray*) colorName;
希望它可以帮助你。