iOS晋级技术文章,请关注 hehuoya.com 合伙呀
默认是底部对齐,其实对的也不齐,
目标效果:
代码:
NSBaselineOffsetAttributeName
基线偏移量:
调整: NSBaselineOffsetAttributeName的值得大小,就可以得到不同的对齐位置
CGFloat fontRatio = 0.16;//基线偏移比率
- 1
CGFloat fontRatio = 0.66;//基线偏移比率
- 1
- (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];
}