计算UILabel的高度?

时间:2011-12-19 21:37:53

标签: iphone objective-c ios

我想知道是否可以获得多行UILabel的高度?我正在开发一个消息传递应用程序,并希望实现类似iPhone消息传递应用程序。

3 个答案:

答案 0 :(得分:1)

您可以使用label.frame.size.height

获取该属性

答案 1 :(得分:1)

您可能需要-[UILabel sizeThatFits:]方法。这是你做的。假设您的UILabel位于变量myLabel中,您已经将其宽度设置为您想要的宽度。

myLabel.text = @"This is my very long message which will probably need multiple lines to be displayed because it is very long.";

CGRect bounds = myLabel.bounds;

// Create a size that is the label's current width, and very very tall.
CGSize prototypeSize = CGSizeMake(bounds.size.width, MAXFLOAT);

// Ask myLabel how big it would be if it had to fit in prototypeSize.
// It will figure out where it would put line breaks in the text to
// fit prototypeSize.width.
CGSize fittedSize = [myLabel sizeThatFits:prototypeSize];

// Now update myLabel.bounds using the fitted height and its existing width.
myLabel.bounds = (CGRect){ bounds.origin, CGSizeMake(bounds.size.width, fittedSize.height) };

答案 2 :(得分:0)

如果你打电话

[label sizeToFit];

它会将UILabel的大小调整为保存所有内容所需的最小大小。然后你可以做label.frame.size.height以获得标签的高度,其中包含该文本量。