根据线数调整高度

时间:2013-11-30 18:31:20

标签: ios uilabel

我正在尝试根据插入的文本行数来调整视图的高度。然后[title numberOfLines]总是返回0而不是新的行数。有没有办法获得当前行数?

UILabel *title = [[ UILabel alloc] initWithFrame:CGRectMake(0, 80, 320, 50)];
[title setNumberOfLines:0];
float height = 32 * [title numberOfLines];
[self setFrame:CGRectMake(0, yCoord, 320, height)];

2 个答案:

答案 0 :(得分:1)

我认为您的问题来自于您没有为UILabel设置任何文字和字体的事实。

您可以使用的是[UIView sizeToFit]

以下是一个简短的示例代码:

    UILabel *title = [[ UILabel alloc] initWithFrame:CGRectMake(0, 80, 320, 50)];
    [title setText:@"An awesome title very long or something really important like a Lorem Ipsum"]; // a text to base the needed numbers of line on
    [title setFont:[UIFont systemFontOfSize:18]]; // don't forget the font
    [title setNumberOfLines:0];
    [title sizeToFit]; // now the label will be resize to display all lines
    [title setFrame:CGRectMake(0, 80, 320, title.frame.size.height)]; // reset the width in case the sizeToFit method resized it wrong.

答案 1 :(得分:0)

结束使用

[title sizeToFit];
int numLines = (int)(title.frame.size.height/title.font.leading);

来自另一个答案