ios代码使用boundingRectWithSizecalcuate标签的高度:选择:属性:上下文返回值40像素超过它 - ios code to calcuate the height of label using boundingRectWithSize:options:attributes:context return a value which is 40 pixels more than it should

- 此内容更新于:2015-12-18
主题:

我有下面的代码,计算我的标签的高度取决于我的文本标签。但是我发现它总是超过40像素应该(我反复试验发现价值40)。谁有同样的问题?如果是的,可能的解决方案是什么?谢谢你!

原文:

I have the following code which calculate the height of my label depends on the text I set the label to. But what I find out is it is always 40 pixels more than it should (I trial and error to find that value 40). Does anyone have the same problem? If yes, what is the possible solution?

    NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:myLabel.font
                                                              forKey:NSFontAttributeName];
     // width is the width of the label
    CGSize size = CGSizeMake(width, NSUIntegerMax);
    CGSize expectedLabelSize =
    [text boundingRectWithSize:size
                        options:NSStringDrawingUsesLineFragmentOrigin
                     attributes:stringAttributes
                        context:nil].size;

// expectedLabelSize.height is 40 pixel than it should.
// If I manually - 40 from the value expected

Thank you.

网友:40比预期更多的任何字符串吗?你期望(为什么)?是什么字体,宽度,和文本测试?

(原文:Is it 40 more than expected for any string? What do you expect (and why)? What is the font, width, and text you are testing with?)

解决方案:
你有试过的其他方式计算高度?首先你的财产你的标签。然后简单地调用你的标签得到其固有的大小,然后得到高度。这对我来说很简单所以我使用它所有的时间。
原文:

Have you tried the other way of calculating the height?

First you set the preferredMaxLayoutWidth property of your label.

Then simply call intrinsicContentSize of your label to get its intrinsic size, then get the height.

It is simpler for me so I use it all the time.