iOS:UILabel动态高度使用sizeWithFont:constrainedToSize:lineBreakMode:不工作 [英] iOS: UILabel dynamic height using sizeWithFont:constrainedToSize:lineBreakMode: not working
问题描述
我试图给出我的 UILabel
动态高度,以便我的其他标签的布局在横向和纵向中看起来都是正确的。
I am trying to give my UILabel
dynamic height so that my layout of other labels looks correct in both landscape and portrait.
在肖像画中,我的文字换行到第二行,而在横向画面中却没有。因此,当使用 sizeWithFont:constrainedToSize:lineBreakMode:
我在双向旋转时获得相同的高度,当我假设当文本为2行时它将是一个更大的数字。
In portrait, my text wraps to the second line, in landscape it does not. So, when using sizeWithFont:constrainedToSize:lineBreakMode:
I get the same height when rotating both ways, when I had assumed it would be a larger number when the text was 2 lines.
当它有两行文字或更多(肖像)时,如何获得 UILabel
的高度在景观中获得一行的新高度?
How can I get the height of my UILabel
when it has two lines of text or more (portrait) and get the new height which is one line, when in landscape?
我想我不理解如何使动态高度工作...
I guess I am not understanding how to get dynamic height working...
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
to
change the line where you set maximumLabelSize
to
CGSize maximumLabelSize = CGSizeMake(headerView.bounds.size.width, CGFLOAT_MAX);
这篇关于iOS:UILabel动态高度使用sizeWithFont:constrainedToSize:lineBreakMode:不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!