【问题标题】:How do I get -[NSString sizeWithFont:forWidth:lineBreakMode:] to work?如何让 -[NSString sizeWithFont:forWidth:lineBreakMode:] 工作?
【发布时间】:2012-02-04 00:50:39
【问题描述】:

我更新了我的问题“Sizing a UILabel (in the iPhone SDK) to fit?”,并用建议的解决方案描述了我的问题,但没有得到答案。或许我可以通过提出一个新问题来获得更好的结果...

我在下面的代码之后设置了一个断点:

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。看起来更像。

【问题讨论】:

  • 我得到了完全相同的结果:21。任何人都知道这个数字来自哪里,或者它只是基于那个字体大小。愚蠢的方法。
  • 如果您使用的是 UITextView,请在此处查看我的答案:stackoverflow.com/questions/2330939/…

标签: cocoa-touch


【解决方案1】:

该高度以像素为单位。我希望它会被截断,即如果您将此文本设置在 1 行的 UILabel 上,则会为您提供您会看到的指标。

尝试使用sizeWithFont:constrainedToSize:,只需将MAXFLOAT 作为尺寸的高度分量。

【讨论】:

  • 如果文本足够长,创建一个最大高度为MAXFLOAT的视图会导致应用崩溃。
【解决方案2】:

任何对此感到困惑的人都知道,该方法命名不当,而且与您的预期不一致(这违反了良好的 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_MAXCGGeometry 中定义)

顺便说一句,但相当重要:所有核心图形都处理点而不是像素。

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

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

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 2013-09-27
    • 1970-01-01
    • 2011-05-04
    • 2011-04-07
    • 2011-07-27
    • 2011-03-08
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多