一、与UILabel相关的冷知识
1. 可以重写UILabel的这个方法来给Label增加内嵌边距
- (void)drawTextInRect:(CGRect)rect;
效果如下:
2. 利用UILabel来显示有段落格式的字符串发现的一些问题
A. 场景一:给label添加行间距,但不限制行数和高度,代码和效果如下:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineSpacing = 10;
paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSParagraphStyleAttributeName:paraStyle}];
label.attributedText = attStr;
B. 场景二:给label添加行间距,不限制高度,限制行数,代码和效果如下:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineSpacing = 10;
paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSParagraphStyleAttributeName:paraStyle}];
label.attributedText = attStr;
label.numberOfLines = 9;
C. 场景三:给label添加首行缩进,但不限制行数和高度,代码和效果如下:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.firstLineHeadIndent = 34;
paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSParagraphStyleAttributeName:paraStyle}];
label.attributedText = attStr;
D. 场景四:给label添加首行缩进,不限制高度,限制行数,代码和效果如下:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.firstLineHeadIndent = 34;
paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSParagraphStyleAttributeName:paraStyle}];
label.attributedText = attStr;
label.numberOfLines = 9;
E. 场景五:给label同时添加首行缩进和行高,但不限制行数和高度,代码和效果如下:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.firstLineHeadIndent = 34;
paraStyle.lineSpacing = 10;
paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSParagraphStyleAttributeName:paraStyle}];
label.attributedText = attStr;
F. 场景五:给label同时添加首行缩进和行高,但不限制高度,限制行数,代码和效果如下:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.firstLineHeadIndent = 34;
paraStyle.lineSpacing = 10;
paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSParagraphStyleAttributeName:paraStyle}];
label.attributedText = attStr;
label.numberOfLines = 9;
小结:当label的设定行数 < 文本的实际行数时,且label的文本同时还拥有行高和首行缩进的段落格式,自动布局时,label实际显示出来的高度是会多出一个行距的高度的。