直接上图
使用NSMutableAttributedString的NSBaselineOffsetAttributeName属性
+ (NSMutableAttributedString *)attributedStringWithString:(NSString *)string
startRanges:(NSArray *)startRanges
endRanges:(NSArray *)endRanges
fonts:(NSArray *)fonts
colors:(NSArray *)colors
baselineOffsets:(NSArray *)baselineOffsets
{
NSMutableAttributedString * attriString = [[NSMutableAttributedString alloc] initWithString:string];
for ( int i = 0; i < fonts.count; i++ )
{
UIFont * font = [UIFont systemFontOfSize:10];
if ( [fonts[i] isKindOfClass:[NSString class]] )
{
NSString * fontStr = fonts[i];
font = [UIFont systemFontOfSize:fontStr.floatValue];
}
else
{
font = fonts[i];
}
UIColor * color = [UIColor blackColor];
if ( [colors[i] isKindOfClass:[NSString class]] )
{
NSString * colorStr = colors[i];
color = [self colorWithHexString:colorStr];
}
else
{
color = colors[i];
}
NSNumber * startIndex = startRanges[i];
NSNumber * endIndex = endRanges[i];
NSRange range = NSMakeRange( startIndex.floatValue, endIndex.floatValue);
NSNumber * baselineOffset = baselineOffsets[i];
[attriString addAttributes:@{
NSFontAttributeName:font,
NSForegroundColorAttributeName:color,
NSBaselineOffsetAttributeName : baselineOffset
}
range:range];
}
return attriString;
}
+ (UIColor *)colorWithHexString:(NSString *)hexString {
unsigned int red,green,blue;
NSRange range;
range.length = 2;
range.location = 0;
[[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&red];
range.location = 2;
[[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&green];
range.location = 4;
[[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&blue];
return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green / 255.0f) blue:(float)(blue / 255.0f)alpha:1.0f];
}
PS:里面的colorWithHexString方法,一般你们自己写就行了
用法
NSString * one = @"1234";
NSString * two = @"56";
NSString * three = @"789";
NSString * four = @"abc";
NSString * string = [NSString stringWithFormat:@"%@%@%@%@",one, two, three, four];
NSArray * startRanges = @[@(0), @(one.length), @(one.length + two.length), @(one.length + two.length + three.length)];
NSArray * endRanges = @[@(one.length), @(two.length), @(three.length), @(four.length)];
NSArray * fonts = @[@"20", @"10", @"25", @"10"];
NSArray * colors = @[@"373737", @"123456", @"F52826", @"A57585"];
NSArray * baselineOffsets = @[@0, @10, @0, @0];
NSMutableAttributedString * attributedString = [APPTheme attributedStringWithString:string
startRanges:startRanges
endRanges:endRanges
fonts:fonts
colors:colors
baselineOffsets:baselineOffsets];
self.label.attributedText = attributedString;