• (转)解决NSMutableAttributedString富文本,不同文字大小水平轴对齐问题(默认底部对齐)


    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];
    }

  • 相关阅读:
    redis 高级功能,过期事件监听
    三五个人的技术团队用的上的技术架构
    听说过api,但是你听说过spi吗
    PostgreSQL建表及相关
    shell命令 $(cd `dirname $0`; pwd);[ "$#" -ne "8" ];exit;declare;`date +%s`
    学习Shell命令
    Shell echo命令
    Linux常用命令
    Linux 目录结构
    nohup ./startWebLogic.sh >out.log 2>&1 & 解析
  • 原文地址:https://www.cnblogs.com/huntaiji/p/9285306.html
Copyright © 2020-2023  润新知