I think I have found an edge case for sizeWithFont:constrainedToSize: where, on a retina display, it will sometimes (it seems based on word wrapping) returns a height 1 line taller than is actually needed, and more importantly than is it actually draws.
NOTE: The real code I am using is buried inside performant centric hand drawn variable height table view cell code, so I've distilled the issue down to as simple a bit of sample code as possible. (Please take note of this when trying to answer something other than my question :-)
This sample UIView fills it's content, measures the text to fit (wrapped), fills that rect, then draws the text.
On a retina device (or simulator) the height is returned 1 line too tall, but on a pre-retina device (or simulator) it returns the correct height.
I would greatly appreciate any insight anyone may have, as it is a bug i'd like to fix!
Much Thanks!
-eric
- (void)drawRect:(CGRect)rect {
NSString * theString = @"Lorem ipsum dolor sit ameyyet, consectetur adipiscing elit. Etiam vel justo leo. Curabitur porta, elit vel.";
UIFont * theFont = [UIFont systemFontOfSize:12];
CGSize theConstraint = CGSizeMake(rect.size.width - 20, rect.size.height - 20);
CGSize theResultSize = [theString sizeWithFont:theFont constrainedToSize:theConstraint];
// dump the measurements
NSLog(@"returned a size h = %f, w = %f", theResultSize.height, theResultSize.width);
// fill the whole rect
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor yellowColor] set];
CGContextFillRect(context, rect);
// fill the measured rect
CGRect theRect = CGRectMake(10, 10, theResultSize.width, theResultSize.height);
context = UIGraphicsGetCurrentContext();
[[UIColor cyanColor] set];
CGContextFillRect(context, theRect);
// draw the text
[[UIColor blackColor] set];
[theString drawInRect:theRect withFont:theFont];
}
The whole simple project is available here.
Simulator Images:
http://files.droplr.com/files/9979822/aLDJ.Screen%20shot%202011-01-11%20at%2012%3A34%3A34.png
http://files.droplr.com/files/9979822/YpCM.Screen%20shot%202011-01-11%20at%2012%3A36%3A47.png
It seems to be an issue with your simulator. This is what I got when I ran it with a Retina simulator on OS 4.3.2
Following is the method I use to find the height of label for dynamic text content. This works fine in my app
- (float)getHeightFortheDynamicLabel:(NSString *)stringForTheLabel
{
UITextView *aSampleTextView;
// 30 is the minimum height
aSampleTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, mywidth, 30)];
aSampleTextView.text = stringForTheLabel;
aSampleTextView.font = [UIFont systemFontOfSize:kMyFontSize];
aSampleTextView.alpha = 0;
[self.view addSubview:aSampleTextView];
float textViewHeight = aSampleTextView.contentSize.height;
[aSampleTextView removeFromSuperview];
[aSampleTextView release];
return textViewHeight;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With