How can I compute the number of lines of a UILabel with a fixed width? [duplicate]

断了今生、忘了曾经 提交于 2019-12-30 00:35:08

问题


How can I compute the number of lines of a UILabel with a fixed width and a given text ?


回答1:


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);
}

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.




回答2:


First get the height of the label from the label size using 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

CGSize sizeOfText = [label.text sizeWithFont:label.font 
                        constrainedToSize:label.frame.size 
                            lineBreakMode:UILineBreakModeWordWrap];
int numberOfLines = sizeOfText.height / label.font.pointSize;



回答3:


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.



来源:https://stackoverflow.com/questions/15161348/how-can-i-compute-the-number-of-lines-of-a-uilabel-with-a-fixed-width

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!