如何查找UILabel的实际行数? [英] How to find actual number of lines of UILabel?
问题描述
如何使用 text <初始化 UILabel
后,如何找到实际行数和字体
?我已将 numberOfLines
属性设置为 0
,因此它将扩展为需要很多行。但是,在设置文本
之后,我怎样才能知道它最终获得了多少行?
How can I find the actual number of lines of a UILabel
after I have initialized it with a text
and a font
? I have set its numberOfLines
property to 0
, so it will expand to however many lines are necessary. But then, how can I find out how many lines it finally got after I set its text
?
我发现了类似的问题,但似乎没有一个提供简洁的答案,而且在我看来,在没有任何开销的情况下获取它必须非常容易。 boundingRectWithSize
或 sizeWithFont
,...
I found similar questions, but none seems to provide a concise answer and it seems to me that it must be really easy to get it without any overhead on juggling around with the boundingRectWithSize
or sizeWithFont
,...
推荐答案
首先在UILabel中设置文本
第一个选项:
首先根据字体计算文本的高度:
Firstly calculate height for text according to font :
NSInteger lineCount = 0;
CGSize labelSize = (CGSize){yourLabel.frame.size.width, MAXFLOAT};
CGRect requiredSize = [self boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: yourLabel.font} context:nil];
现在计算行数:
int charSize = lroundf(yourLabel.font.lineHeight);
int rHeight = lroundf(requiredSize.height);
lineCount = rHeight/charSize;
NSLog(@"No of lines: %i",lineCount);
第二选项:
NSInteger lineCount = 0;
CGSize textSize = CGSizeMake(yourLabel.frame.size.width, MAXFLOAT);
int rHeight = lroundf([yourLabel sizeThatFits:textSize].height);
int charSize = lroundf(yourLabel.font.lineHeight);
lineCount = rHeight/charSize;
NSLog(@"No of lines: %i",lineCount);
这篇关于如何查找UILabel的实际行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!