iOS:UILabel动态高度使用sizeWithFont:constrainedToSize:lineBreakMode:不工作

时间:2011-04-04 22:59:01

标签: iphone ios uiview uilabel

我正在尝试给出UILabel动态高度,以便我的其他标签的布局在横向和纵向中看起来都是正确的。

在肖像中,我的文字包裹到第二行,在横向上它不包含。因此,当使用sizeWithFont:constrainedToSize:lineBreakMode:时,我在双向旋转时获得相同的高度,当我假设当文本为2行时它将是一个更大的数字。

如果UILabel有两行文字或更多(纵向),并且在横向拍摄时获得一行的新高度,我怎样才能获得UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, top, screen.size.width - 20, 200.0f)]; itemTitle.text = self.newsAsset.title; itemTitle.adjustsFontSizeToFitWidth = NO; itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth; itemTitle.font = [UIFont boldSystemFontOfSize:18.0]; itemTitle.textColor = [UIColor blackColor]; itemTitle.shadowColor = [UIColor whiteColor]; itemTitle.shadowOffset = CGSizeMake(0, 1); itemTitle.backgroundColor = [UIColor blueColor]; itemTitle.lineBreakMode = UILineBreakModeWordWrap; itemTitle.numberOfLines = 0; [itemTitle sizeToFit]; // Set the height CGSize maximumLabelSize = CGSizeMake(300,9999); CGSize titleSize = [itemTitle.text sizeWithFont:itemTitle.font constrainedToSize:maximumLabelSize lineBreakMode:itemTitle.lineBreakMode]; NSLog(@"Height: %.f Width: %.f", titleSize.height, titleSize.width); //Adjust the label the the new height CGRect newFrame = itemTitle.frame; newFrame.size.height = titleSize.height; itemTitle.frame = newFrame; // Add them! [headerView addSubview:itemTitle]; [itemTitle release]; top += titleSize.height; 的高度?

我想我不明白如何让动态高度工作......

{{1}}

2 个答案:

答案 0 :(得分:3)

将您设置为maximumLabelSize的行更改为

CGSize maximumLabelSize = CGSizeMake(headerView.bounds.size.width, CGFLOAT_MAX);

答案 1 :(得分:0)

在您现在的代码中,无论在哪个方向,您都将获得相同的宽度和高度,因为您始终将宽度300传递给sizeWithFont方法。如果您将其设置为动态,则sizeWithFont的结果也可能会动态更改。