NSString sizeWithFont:用于多行?
是否有相当于 NSString 的 sizeWithFont: 方法可用于计算 UITectView 中给定宽度的文本高度?据我所知,NSString 中的所有方法都只在一行上运行。
Is there an equivalent to NSString's sizeWithFont:
method that can be used for calculating the height of text in a UITectView for a given width? All of the methods from NSString only operate on a single line from what I can tell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 苹果对于这些 NSString 方法的参考,您可以使用
-sizeWithFont:constrainedToSize:
或-sizeWithFont:constrainedToSize:lineBreakMode:
来“计算多行文本的指标” 。From Apple's reference for these NSString methods, you could use
-sizeWithFont:constrainedToSize:
or-sizeWithFont:constrainedToSize:lineBreakMode:
for "Computing Metrics for Multiple Lines of Text".对于
UITextView
,您所要做的就是在视图上调用-sizeToFit
,它会自动调整其高度,直到可以容纳所有可用文本。您需要做的就是设置文本视图的宽度,设置文本,然后调用-sizeToFit
。文本视图将调整其高度以适合所有文本。更新:
显然,文本视图仅在高度过高时才会缩小,但如果高度不足以显示所有文本,则文本视图不会增长。此外,一旦调用
-sizeToFit
,文本视图的y
坐标将重置回0.0f
。因此,您要做的就是:首先,设置框架,以便可以根据需要设置宽度。您可以使用 CGFLOAT_MAX 来表示无限高度。接下来,调用
-sizeToFit
缩小高度,直到刚好适合所有文本。但是,它还会重置y
坐标,因此我们继续并再次设置框架以配置x
和y
坐标(在此示例中) ,10.0f
对于x
和y
— 不考虑宽度并保持高度设置为任何-sizeToFit
计算。For
UITextView
, all you have to do is call-sizeToFit
on the view, and it will automatically resize its height until it can fit all the text available. All you need to do is set the width of the text view, set the text, then call-sizeToFit
. The text view will resize its height just enough to fit all the text.UPDATE:
Apparently text views only shrink when there's excess height, but they don't grow if there's insufficient height to display all the text. In addition, once you call
-sizeToFit
, the text view'sy
coordinate is reset back to0.0f
. So here's what you do:First, you set the frame just so you can set the width like you want it. You use
CGFLOAT_MAX
to pretty much indicate infinite height. Next, calling-sizeToFit
shrinks the height until it just fits all the text. However, it also resets they
coordinate, so we go ahead and set the frame again to configure thex
andy
coordinates—in this example,10.0f
for bothx
andy
—, leaving the width alone and keeping the height set to whatever-sizeToFit
calculated.实际上,您可以使用属性 contentSize。
actually, you could use the property contentSize.