UILabel中字体换行且显示不同的字体

问题

项目中的需求是显示单词的中英文,而且单词的字体需要随着单词字母的数量来动态的改变自己的”font”,同时需要将中英文设置为不同的颜色

难点

单词的中英文字体数量不是成比例变化的,即中英文的翻译可能差别很大,如果用俩个label分别显示,很难让俩者字体同时变化

思路

首先联想到的是UILabel的富文本属性,将中英文拼接起来,用一个label来显示

解决步骤

  1. 将中英文拼接起来,同时将中英文换行处理
1
2
3
NSString *str2 = @"影魔";
NSString *str3 = @"NEVERMORE";
NSString *str1 = [NSString stringWithFormat:@"%@\n%@",str2,str3];
  1. 对拼接起来的字符串进行Range处理,对不同段的数据进行不同的赋值
1
2
3
4
5
6
7
8
9
10
11
12
NSRange range1 = [str1 rangeOfString:@"\n"];
NSString *b = [str1 substringFromIndex:str1.length - 1];
NSRange range2 = [str1 rangeOfString:b];
NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc]initWithString:str1];
//第一段
[attributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, range1.location)];
[attributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:66] range:NSMakeRange(0, range1.location)];
//第二段问题代码
[attributed addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(range1.location, range2.location - range1.location + 1)];
[attributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:44] range:NSMakeRange(range1.location, range2.location - range1.location + 1)];
  1. 创建UILabel来接收,并且设置label的一些属性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    self.textLabel = [[UILabel alloc] init];
    self.textLabel.attributedText = attributed;
    self.textLabel.adjustsFontSizeToFitWidth = YES;
    self.textLabel.numberOfLines = 2;
    self.textLabel.textAlignment = NSTextAlignmentLeft;
    self.textLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    [self.view addSubview:self.textLabel];
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.view.mas_top).offset(55);
    make.centerX.mas_equalTo(self.view.mas_centerX);
    make.width.mas_equalTo(240);
    make.height.mas_equalTo(70);
    }];

实际效果图

;

从图中发现奇怪的现象,就是没全部设置,这是由于第二段的代码NSRange范围出了问题,由于获取的是最后一个字母,然后当有重复的字母的时候如此例中的”d”,会导致范围出错

重新设置范围

 NSRange range3 = NSMakeRange(range1.location, str1.length - range1.location);
//    第二段正确代码
[attributed addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range3];
[attributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:44] range:range3];

正确的效果图

;

这个人很帅<br>他什么都不想说<br>