为什么我的sizeWithFont:constrainedToSize:lineBreakMode:总是返回零?

Tri*_*riz 4 iphone cocoa-touch nsstring

我正在尝试创建一个UITableViewCell,根据它显示的字符串的长度来调整它的高度,但是我对此方法感到困惑.

这是我得到的:

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];
Run Code Online (Sandbox Code Playgroud)

无论如何,stringHeight显示为0.我错过了什么?

谢谢!

rpe*_*ich 11

CGFloats对应C float数据类型; 适当的格式说明符是%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];
Run Code Online (Sandbox Code Playgroud)

此外,你应该使用CGFLOAT_MAX而不是MAXFLOAT

  • 这里更好的常数可能是CGFLOAT_MAX,但没有使用MAXFLOAT的危险.要么比选择一个随机的大数字更清楚,这可能被后来的读者解释为故意限制. (2认同)

tom*_*ple 5

你也可以用

NSStringFromCGSize(theSize);
Run Code Online (Sandbox Code Playgroud)