Correct way to use sizeThatFits: and sizeToFit with UILabel?

Thomas Clayson picture Thomas Clayson · Oct 26, 2010 · Viewed 8.4k times · Source

At the moment I have a label being sized correctly using [aString sizeWithFont:constrainedToSize:lineBreakMode:] but I've introduced rotation into my device and with a flexible width and height this results in my UILabel stretching width ways (because its set relative to the main view) but not then contracting height-wise to compensate for the extra space.

In another question I asked I was told to use sizeToFit and/or sizeThatFits: however I can't find any useful resource on the internet that tells me how to use this appropriately and trials I've done result in irrational behavior.

In a nutshell, lets say I have a structure like this:

UIView *innerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0)];
[innerView setAutoresizingMask:*flexible width and height*]
[innerView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:innerView];

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, innerView.frame.size.width-20, 0)];
[myLabel setAutoresizingMask:*flexible width and height*]
[myLabel setBackgroundColor:[UIColor blueColor]];
[myLabel setNumberOfLines:0];
[myLabel setLineBreakMode:UILineBreakModeWordWrap];
[innerView addSubview:myLabel];

Thats a simplified version (also by way of disclaimer, this isn't my acctual code, I realise these elements will leak and everything else... this is just an example so you can see the structure).

Basically I have those two elements. Now on rotation they will both stretch to fit the new view size. What I need is a way to increase or decrease the height to fit the content dynamically. [aString sizeWithFont...] is only static. So how would I use sizeToFit or sizeThatFits to make this dynamic?

Thank you.

Tom

Answer

Tom picture Tom · Jan 21, 2011

Have you tried resetting the frame of your labels after the screen rotation? Check the value of interfaceOrientation in:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

Then, set the label's frame accordingly for each view mode inside didRotateFromInterfaceOrientation.

Here's an example of resizing label frames for string length: http://cocoamatic.blogspot.com/2010/08/uilabel-dynamic-sizing-based-on-string.html