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

问题描述

使用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 设置不一样字体,文字不能居中对齐

解决方法

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;

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

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容