开发过程中,label默认的行间距一般很难满足我们UI设计师的要求!label默认也没有属性可以直接设置行间距,但是我们可以通过attributedText属性设置label展示内容以达到需求!
代码:
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:model.message];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 8.0; // 设置行间距
paragraphStyle.alignment = NSTextAlignmentJustified; //设置两端对齐显示
[attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedStr.length)];
self.labContent.attributedText = attributedStr;
设置字间距,我们只需添加一句代码:
[attributedStr addAttribute:NSKernAttributeName value:@(8) range:NSMakeRange(0, attributedStr.length)];
需要的声明:
-
我们来看一下UIFont的属性:
// Font attributes @property(nonatomic,readonly,strong) NSString *familyName; //字体所在家族的名字 @property(nonatomic,readonly,strong) NSString *fontName; //字体名称 @property(nonatomic,readonly) CGFloat pointSize; //字的大小 @property(nonatomic,readonly) CGFloat ascender; //基准线以上的高度 @property(nonatomic,readonly) CGFloat descender; //基准线以下的高度 @property(nonatomic,readonly) CGFloat capHeight; //最高的字符的高度。 @property(nonatomic,readonly) CGFloat xHeight; //最低的字符的高度。 @property(nonatomic,readonly) CGFloat lineHeight API_AVAILABLE(ios(4.0));//当前字体下的行高 @property(nonatomic,readonly) CGFloat leading; //行间距 /** 从属性上来看,当我们设置 UIFont *font = [UIFont systemFontOfSize:14]; 那么此时pointSize为14,lineHeight则为16.707031, 这里面的高度包含了ascender+descender, 设置的时候UI设计师给我们的行高是 行高+留白 高度,所以,我们设置行高的时候,使用UI设计师给的行高设置出来的效果比实际要大一点! */