Why is my sizeWithFont:constrainedToSize:lineBreakMode: always returning zero?

青春壹個敷衍的年華 提交于 2019-11-29 15:15:52

问题


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!


回答1:


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




回答2:


You could also use

NSStringFromCGSize(theSize);


来源:https://stackoverflow.com/questions/1352735/why-is-my-sizewithfontconstrainedtosizelinebreakmode-always-returning-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!