iOS: UILabel dynamic height using sizeWithFont:con

2019-03-30 16:05发布

问题:

I am trying to give my UILabel dynamic height so that my layout of other labels looks correct in both landscape and portrait.

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.

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;

回答1:

change the line where you set maximumLabelSize to

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


回答2:

In your code as it is now, in either orientation you will get the same width and height, since you always pass a width of 300 to the sizeWithFont method. If you make it dynamic, maybe the result of the sizeWithFont will also change dynamically.