解决使用NSMutableAttributedString 设置不同字体,文字不能居中对齐

来源:互联网 发布:手机淘宝排名怎么提升 编辑:程序博客网 时间:2024/06/05 15:07
  • 问题描述

使用NSMutableAttributedString设置不同字体,

     int  a = 50;     int b = 10;    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"10元抵现券"];    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:a] range:NSMakeRange(0, 2)];    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:b] range:NSMakeRange(2, attStr.length - 2)];//     [attStr addAttribute:NSBaselineOffsetAttributeName value:@(0.36 * (a - b)) range:NSMakeRange(2, attStr.length - 2)];    label.attributedText = attStr;

文字不能居中对齐;如图:

这里写图片描述

  • 解决方法
    NSMutableAttributedString 添加NSBaselineOffsetAttributeName这个Attribute
[attStr addAttribute:NSBaselineOffsetAttributeName value:@(0.36 * (a - b)) range:NSMakeRange(2, attStr.length - 2)];

value = 0.36 * (大字号 - 小字号)

    int  a = 50;    int b = 10;    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"10元抵现券"];    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:a] range:NSMakeRange(0, 2)];    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:b] range:NSMakeRange(2, attStr.length - 2)];     [attStr addAttribute:NSBaselineOffsetAttributeName value:@(0.36 * (a - b)) range:NSMakeRange(2, attStr.length - 2)];    label.attributedText = attStr;
  • 效果图
    这里写图片描述
0 0