4

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;
D-eptdeveloper
  • 2,430
  • 1
  • 16
  • 30
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

2 Answers2

3

change the line where you set maximumLabelSize to

CGSize maximumLabelSize = CGSizeMake(headerView.bounds.size.width, CGFLOAT_MAX);
Jochen
  • 606
  • 6
  • 23
0

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.

mvds
  • 45,755
  • 8
  • 102
  • 111
  • Ok, and so what would I do to fix this? – Nic Hubbard Apr 04 '11 at 23:17
  • maybe use `screen.size.width - 20` instead of 300, like you do in the alloc/init line? And I would also NSLog() anything that may be of interest, e.g. `NSLog(@"screen size: %@",NSStringFromCGSize(screen.size));` – mvds Apr 04 '11 at 23:20
  • (just to make sure that the screen orientation change does in fact result in the flipped screen size at that point) – mvds Apr 04 '11 at 23:21