iOS label富文本解决行间距和不同字号文案上居中问题

最近的项目开发过程中,遇到了一个文案显示问题,难点是:
1.文案只显示两行,但是第一行显示的宽度不确定,而且部分文案不确定;
2.总共两行的文案,要显示3种不一样字体和2种不一样的颜色;
3.第1行两种字号不一样的文案还要居中对齐,居中对齐。如下图所示:


文案样式

针对这个问题,从代码的简介性、易读性以及UI效果上考虑,最好能用一个label实现。那么就要解决两个问题:
1.显示2行文案,以及能够自由控制行间距;
2.第一行文案能够正确显示,而且不同字号的文案能够居中对齐。
第一步,解决第一行文案宽度问题,虽然第一行有不确定的文案,但是第二行文案确定,我们可以直接截取;获取文案后,计算文案的宽度,设置label的宽度。

//通过字号和文案计算宽度
- (CGSize)completeTextWidthWithFont:(CGFloat)fontSize text:(NSString *)text
{
    NSDictionary *attrs = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:fontSize]};
    CGSize size = [text sizeWithAttributes:attrs];
    return size;
}

第二步,可以调整行间距以及第一行上居中问题,代码如下所示:

    - (void)setupSubview
{
    NSString *str = @"¥3000额度";
    self.label = [[UILabel alloc] init];
    self.label.numberOfLines = 2;
    //基准线-用来对齐,可以调整为其他数
    CGFloat fontRatio = 0.26;
    //调整行间距方法2
   // [self.label setValue:@(25) forKey:@"lineSpacing"];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8];
    //调整行间距方法2
    [attrStr addAttribute:NSParagraphStyleAttributeName
                   value:paragraphStyle
                   range:NSMakeRange(0, str.length)];
    NSRange rang = [str rangeOfString:@"额度"];
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor]
                    range:NSMakeRange(0, 1)];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12]
                    range:NSMakeRange(0, 1)];
    //24是文案3000的字号 12是¥的字号 fontRatio-基准线
    [attrStr addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (24-12)) range:NSMakeRange(0, 1)];
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor]
                    range:NSMakeRange(1, rang.location)];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:24]
                    range:NSMakeRange(1, rang.location)];
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]
                    range:rang];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18]
                    range:rang];
    self.label.attributedText = attrStr;
    //居中
    self.label.textAlignment = NSTextAlignmentCenter;
    //计算第一行文案的宽度
    CGSize size1 = [self completeTextWidthWithFont:12 text:@"¥"];
    CGSize size2 = [self completeTextWidthWithFont:24 text:[str substringWithRange:NSMakeRange(1, rang.location)]];
    self.label.frame = CGRectMake(100, 100, size1.width + size2.width,
                                  size1.height + size2.height + 20);
    [self.view addSubview:self.label];
}

你可能感兴趣的:(iOS label富文本解决行间距和不同字号文案上居中问题)