views:

1193

answers:

1

I'm trying to make a UITableViewCell that adjusts its height based on the length of a string it's displaying, but am getting hung up on this method.

Here's what I've got:

NSString *text = @"A really long string in here";
CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
NSString *stringHeight = [NSString stringWithFormat:@"%d", theSize.height];

No matter what, stringHeight displays as 0. What am I missing?

Thanks!

+5  A: 

CGFloats correspond to the C float data type; the proper format specifier for them is %f:

 NSString *text = @"A really long string in here"; 
 CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
 NSString *stringHeight = [NSString stringWithFormat:@"%f", theSize.height];

Also, you should use CGFLOAT_MAX instead of MAXFLOAT

rpetrich
Ahhh, switching to `%f` totally worked. I was under the impression that `%d` worked for `floats` too, but that clearly isn't the case. `MAXFLOAT` seems to work fine, though it would work just as well with a suitably large number. Thanks for the quick response!
Triz
Also, `%d` = signed int, not double (it's the same as `%i`). `%f` (or `%lf`) will work for both floats and doubles.(Also, under 64-bit, CGFloat is a double, but that obviously doesn't apply here.)
Wevah
The better constant here is probably CGFLOAT_MAX, but there's no danger of using MAXFLOAT. Either is clearer than picking a random large number, which might be interpreted by later readers as an intentional limit.
Rob Napier
Thanks for the input; I've removed the erroneous information regarding doubles and switched to CGFLOAT_MAX
rpetrich