iOS:使用sizeWithFont的UILabeldynamic高度:constrainedToSize:lineBreakMode:不工作

我试图给我的UILabeldynamic高度,以便我的其他标签的布局在横向和纵向上看起来都是正确的。

在纵向,我的文字包装到第二行,在横向上它不。 所以,当使用sizeWithFont:constrainedToSize:lineBreakMode:我得到了同样的高度旋转双方,当我认为这将是一个更大的数字,当文本是2行。

如何获得我的UILabel的高度,当它有两行文字或更多(肖像),并得到新的高度是一个线,在横向?

我想我不理解如何获得dynamic高度工作…

 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; 

将您设置maximumLabelSize的行更改为

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

在你的代码中,无论在哪一个方向,你都将得到相同的宽度和高度,因为你总是将sizeWithFont方法的宽度传递给300。 如果你使它dynamic的,也许sizeWithFont的结果也会dynamic改变。