开发者

NSString sizeWithFont:constrainedToSize: not working as expected

I'm attempting to use size开发者_StackOverflow中文版WithFont as follows:

[commentTextLabel.text sizeWithFont:commentTextLabel.font
                  constrainedToSize:CGSizeMake(commentTextLabel.frame.size.width, CGFLOAT_MAX)
                      lineBreakMode:UILineBreakModeWordWrap];

When I do this, I would expect the CGSize returned to have the same width as was passed in (commentTextLabel.frame.size.width) However, for some reason, the width is getting reduced despite the fact that the text has plenty of vertical room to grow.

Here are the values I'm seeing:

  • In: 360.000000, CGFLOAT_MAX
  • Out: 335.000000, 88.000000

Am I simply misunderstanding the function? If so, how could I implement this to determine the height of the text when constrained to a certain width?


What is the contents of your string and the size of your font?

It seems to me that it's wrapping words as you expected and returning the minimum size required to contain the result. Note your Out width is only 25 points less that your In. Unless your string wrapped at exactly 360 points you would expect the resulting width to be less than your constrained size.


After some playing around with it, what I believe is happening is that the text is wrapping in such a way that the longest line is only 335 pixels wide. The solution I'm using is to only use the height returned by this function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜