开发中发现的一些容易忽略的冷知识(持续更新)

2019-12-20  本文已影响0人  偷偷看简书

一、与UILabel相关的冷知识

1. 可以重写UILabel的这个方法来给Label增加内嵌边距

 - (void)drawTextInRect:(CGRect)rect;

效果如下:


拥有内嵌边距的UILabel样式,灰色视图是label

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实际显示出来的高度是会多出一个行距的高度的。

上一篇下一篇

猜你喜欢

热点阅读