2009-01-07 107 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以獲取「點對像素」。