zoukankan      html  css  js  c++  java
  • (转)解决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];
    }

  • 相关阅读:
    240. Search a 2D Matrix II
    442. Find All Duplicates in an Array
    4. Median of Two Sorted Arrays
    3. Longest Substring Without Repeating Characters
    poj 3616
    cf 337 div2 c
    poj 2385
    poj 2229
    uvalive 3231
    Entity Framework 学习初级篇7--基本操作:增加、更新、删除、事务
  • 原文地址:https://www.cnblogs.com/huntaiji/p/9285306.html
Copyright © 2011-2022 走看看