我更新了我的问题" 调整UILabel(在iPhone SDK中)以适应? ",并在建议的解决方案中描述了我的问题,但没有得到答案.也许我会通过提出一个新问题来获得更好的结果......
我在以下代码后设置了一个断点:
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.这似乎更像.
该高度以像素为单位.我希望它是截断的,即如果你在UILabel上用1行设置这个文本,你会看到你所看到的指标.
尝试使用sizeWithFont:constrainedToSize:
,只需给它MAXFLOAT
大小的高度组件.
任何困惑这一点的人都会学习,这种方法名称不恰当,与你期望的相反(这违反了良好的API设计,但正如任何经验丰富的开发人员所知道的那样:Apple的API设计不好,对不起家伙).值得一读:Josh Bloch关于良好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的文档和Command + F,了解"Points vs Pixels".