如何计算具有固定宽度的UILabel的行数?
问题描述:
如何计算具有固定宽度和给定文本的UILabel的行数?
How can I compute the number of lines of a UILabel with a fixed width and a given text ?
答
此代码假设标签
具有所需的文本,并且其框架已设置为所需的宽度。
This code assumes label
has the desired text and its frame is already set to the desired width.
- (int)lineCountForLabel:(UILabel *)label {
CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX);
CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap];
return ceil(size.height / label.font.lineHeight);
}
更新:
如果您只想根据文本和当前宽度确定标签所需的高度,请将其更改为:
If all you want is to determine the required height for the label based on its text and current width, then change this to:
- (CGSize)sizeForLabel:(UILabel *)label {
CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX);
CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap];
return size;
}
返回的尺寸
是包含标签的正确宽度和高度。
The returned size
is the proper width and height to contain the label.