2009-01-07 106 views
21

我更新了我的问题“Sizing a UILabel (in the iPhone SDK) to fit?”,并提供了一个建议解决方案的问题描述,但没有得到答案。也许我会问一个新问题有更好的结果...如何获取 - [NSString sizeWithFont:forWidth:lineBreakMode:]工作?

我把下面的代码后断点:

NSString *theText = @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation."; 
CGSize theSize = [theText sizeWithFont:[UIFont systemFontOfSize:17.0f] forWidth:260.0 lineBreakMode:UILineBreakModeWordWrap]; 

theSize.height是21 theSize.width是231什么是我做错了什么?该高度不能以像素或行数为单位。

请注意,[UIFont systemFontOfSize:17.0f]是为了指定默认字体。

更新:我改变了代码:

CGSize constraintSize; 
constraintSize.width = 260.0f; 
constraintSize.height = MAXFLOAT; 
NSString *theText = @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation."; 
CGSize theSize = [theText sizeWithFont:[UIFont systemFontOfSize:17.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

theSize.height是273.这似乎更喜欢它。

+0

我得到了完全相同的结果:21.任何人都知道该数字来自哪里,还是仅仅基于该字体大小。愚蠢的方法。 – ZaBlanc 2011-10-07 20:24:12

+0

如果您使用的是UITextView,请在这里查看我的答案:http://stackoverflow.com/questions/2330939/sizewithfont-doesnt-give-correct-height-for-uitextview-if-there-is-a -long-strin/15408198#15408198 – domsom 2013-03-14 11:40:17

回答

29

该高度以像素为单位。我预计它会被截断,即如果您在UILabel上用1行设置此文本,就会给您提供的指标。

尝试使用sizeWithFont:constrainedToSize:,并只给它MAXFLOAT作为尺寸的高度部分。

7

正如任何一个对此感到困惑的人所了解的,这种方法被错误地命名,并且与您期望的不一致(这违反了良好的API设计,但是任何经验丰富的开发人员都知道:Apple的API设计不好,对不起大家)。值得一读:Josh Bloch's presentation关于良好的API设计。

我假设他们应该重新命名它(如果它必须保留)并使其成为有用的,这样你就不会最终使用传统的CGSize这种通常的做法,太大了。

[someString sizeWithFont:yourFont 
     constrainedToSize:CGSizeMake(maxWidthYouSpecify, self.frame.size.height) 
      lineBreakMode:UILineBreakModeWordWrap]; 

或者这将很好的工作:

[someString sizeWithFont:yourFont 
     constrainedToSize:CGSizeMake(maxWidthYouSpecify, CGFLOAT_MAX) 
      lineBreakMode:UILineBreakModeWordWrap]; 

这一点,可以说,功能应该如何工作。 (FWIW,CGFLOAT_MAX定义在CGGeometry

另一方面,但相当重要:所有核心图形处理的点不是像素。

一点不一定对应于屏幕上的一个像素。

这是一个重要的区别,您需要了解处理不同分辨率(iPhone 3GS vs 4 vs iPad等)时需要了解的区别。请参阅Apple的docs和Command + F以获取“点对像素”。