为什么是我的sizeWithFont

为什么是我的sizeWithFont

本文介绍了为什么是我的sizeWithFont:constrainedToSize:lineBreakMode:总是返回零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图创建一个UITableViewCell,它会根据显示的字符串的长度调整其高度。我有:

  NSString * text = @这里真的很长的字符串; 
CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f,MAXFLOAT)lineBreakMode:UILineBreakModeWordWrap];
NSString * stringHeight = [NSString stringWithFormat:@%d,theSize.height];

无论如何, stringHeight code> 0 。



谢谢!

解决方案

CGFloat 对应于C float 数据类型;它们的正确格式说明符是%f

  NSString * text = @这里真的很长的字符串; 
CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f,CGFLOAT_MAX)lineBreakMode:UILineBreakModeWordWrap];
NSString * stringHeight = [NSString stringWithFormat:@%f,theSize.height];

此外,您应该使用 CGFLOAT_MAX MAXFLOAT


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!

解决方案

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

这篇关于为什么是我的sizeWithFont:constrainedToSize:lineBreakMode:总是返回零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:17