转自:https://blog.csdn.net/kuangdacaikuang/article/details/79584587
解决NSMutableAttributedString富文本,不同文字大小水平轴对齐问题(默认底部对齐)
默认是底部对齐,其实对的也不齐,
目标效果:
代码:
NSBaselineOffsetAttributeName
基线偏移量:
调整: NSBaselineOffsetAttributeName的值得大小,就可以得到不同的对齐位置
CGFloat fontRatio = 0.16;//基线偏移比率
CGFloat fontRatio = 0.66;//基线偏移比率
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"富文本";
NSString *text = @"(2) 3 : 2 (1)";
NSInteger fontSize1 = 30;
NSInteger fontSize2 = 16;
CGFloat fontRatio = 0.66;//基线偏移比率
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(150, 200, 150, 40)];
label.text = text;
NSMutableAttributedString *attributedStringM = [[NSMutableAttributedString alloc] initWithString:text];
[attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize2] range:NSMakeRange(0, 3)];
[attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 3)];
[attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize1] range:NSMakeRange(3, text.length - 6)];
[attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(3, text.length - 6)];
[attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize2] range:NSMakeRange(text.length - 3, 3)];
[attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(text.length - 3, 3)];
//不同大小的文字水平中部对齐(默认是底部对齐)
[attributedStringM addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (fontSize1 - fontSize2)) range:NSMakeRange(0, 3)];
[attributedStringM addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (fontSize1 - fontSize2)) range:NSMakeRange(text.length - 3, 3)];
label.attributedText = attributedStringM;
[self.view addSubview:label];
}