解决使用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;

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


image.png
解决方法

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;
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容