views:

136

answers:

1

Hi all, I am adjusting my old apps to iPhone 4 using the simulator at the moment and I can across a very strange behavior with UILabel drawing and sizeWithFont:constrainedToSize: that I currently see only on the iPhone 4 simulator.

I am trying to show the following error text to the user: @"Incorrect user name or password" This text sits inside a dynamic error box that is built from three parts: top, center and bottom and therefore I calculate the size of the label so I can change the center background image frame accordingly.

Here is an example of the UILabel size calculation code:

CGRect errorFrame = CGRectMake(40, 0, 240.0, 22.0);
UILabel *errorlabel = [[UILabel alloc] initWithFrame:errorFrame];
errorlabel.adjustsFontSizeToFitWidth = NO;
errorlabel.font = [UIFont fontWithName:@"HelveticaNeue" size:16];
errorlabel.textAlignment = UITextAlignmentLeft;
errorlabel.numberOfLines = 0;
errorlabel.text = @"Incorrect user name or password";
// since only the width is fixed I will use a really large height value
CGSize errorLabelSize = [errorlabel.text sizeWithFont:errorlabel.font constrainedToSize:CGSizeMake(240.0, 4600.0)];
CGRect newFrame = errorlabel.frame;
newFrame.size.height = errorLabelSize.height;
errorlabel.frame = newFrame;
    // added so I can easily see the new frame
errorlabel.backgroundColor = [UIColor redColor];
[self.errorView addSubview:errorlabel];
[errorlabel release];

When I run the code on the iPhone 3 simulator the sizeWithFont:constrainedToSize: method returns a height of 1 line and draws this error text on 1 line. When I run the same code on the iPhone 4 simulator sizeWithFont:constrainedToSize: returns a size of (170.0, 42.0) which is needed for two lines but label itself is drawn on 1 line. It is as if the sizeWithFont code doesn't use the same logics of the rendering code.

Since changing the error text is no option :) any idea how to bypass this issue or resolve it?

Thanks in advance

A: 

I've got this same problem, with the same font. I haven't found a way to predict when it will occur, and it appears to never be more than precisely one line extra. It happens on the device exactly as on the simulator. It happens in all of iOS 4.0, 4.0.1, and 4.0.2. I haven't checked on the 4.1 simulator yet.

Eventually I worked around by manually noting the places it occurred and subtracting one line height in these locations. When we upgrade to 4.1 we'll check to see if this behaviour has persisted.

John