ios 如何计算固定宽度的 UILabel 的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15161348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I compute the number of lines of a UILabel with a fixed width?
提问by Alexis
How can I compute the number of lines of a UILabel with a fixed width and a given text ?
如何计算具有固定宽度和给定文本的 UILabel 的行数?
回答by rmaddy
This code assumes label
has the desired text and its frame is already set to the desired width.
此代码假定label
具有所需的文本并且其框架已设置为所需的宽度。
- (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);
}
Update:
更新:
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.
返回的size
是包含标签的正确宽度和高度。
回答by nsgulliver
First get the height of the label from the label size using constrainedSize
首先使用标签大小获取标签的高度 constrainedSize
CGSize labelSize = [label.text sizeWithFont:label.font
constrainedToSize:label.frame.size
lineBreakMode:UILineBreakModeWordWrap];
CGFloat labelHeight = labelSize.height;
once you have the label height then check the number of lines with the font size where fontsize
is the size you are using for your label. e.g it could be 10 or depending on your requirements
获得标签高度后,请检查带有字体大小的行数,其中字体大小fontsize
是您用于标签的大小。例如它可能是 10 或取决于您的要求
CGSize sizeOfText = [label.text sizeWithFont:label.font
constrainedToSize:label.frame.size
lineBreakMode:UILineBreakModeWordWrap];
int numberOfLines = sizeOfText.height / label.font.pointSize;
回答by Charlie Price
You can compute the vertical height necessary to display the string using the sizeWithFont:constrainedToSize:method on NSString. Given that size, you can resize the label to display the entire string.
您可以使用NSString上的sizeWithFont:constrainedToSize:方法计算显示字符串所需的垂直高度。给定该大小,您可以调整标签大小以显示整个字符串。