有这么个需求
直接上代码
UILabel * uplab = [ViewController normalLabelText:@"身份证号"];
[self.view addSubview:uplab];
uplab.frame = CGRectMake(100, 100, 80, 20);
UILabel * downLab = [ViewController normalLabelText:@"姓名"];
[self.view addSubview:downLab];
downLab.frame = CGRectMake(100, 130, 80, 20);
+ (UILabel *)normalLabelText:(NSString *)text{
UILabel * lab = [[UILabel alloc] init];
lab.backgroundColor = [UIColor whiteColor];
lab.text = text;
lab.textColor = [UIColor blackColor];
lab.font = [UIFont systemFontOfSize:16];
return lab;
}
但是这些代码写出来的效果与ui要求的不符,
那怎么办,在姓名之间加 两个空格 吗
no!no!no! 加几个空格也达不到设计图上的效果,这个时候我们要用到 两端对齐的效果了
两端对齐代码如下:
+ (UILabel *)normalLabelText:(NSString *)text{
UILabel * lab = [[UILabel alloc] init];
lab.backgroundColor = [UIColor whiteColor];
CGSize textSize = [text boundingRectWithSize:CGSizeMake(80, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size;
CGFloat margin = (80 - textSize.width) / (text.length - 1);
NSNumber * number = [NSNumber numberWithFloat:margin];
NSMutableAttributedString * attr = [[NSMutableAttributedString alloc] initWithString:text];
[attr addAttribute:NSKernAttributeName value:number range:NSMakeRange(0, text.length - 1)];
lab.attributedText = attr;
lab.textColor = [UIColor blackColor];
lab.font = [UIFont systemFontOfSize:16];
return lab;
}
原理:给字符串添加字符间间距
效果如下