Reputation: 1560
I wanted to know is it possible to get the height of a multi line UILabel
? I'm developing a messaging application and wanted to achieve something like the iPhone messaging application.
Upvotes: 1
Views: 495
Reputation: 385500
You probably want the -[UILabel sizeThatFits:]
method. Here's what you do. Let's say your UILabel is in the variable myLabel
, and you've already set its width to whatever you want.
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) };
Upvotes: 2
Reputation: 2403
If you call
[label sizeToFit];
it will resize the UILabel to the minimum size needed to hold all the content. Then you can just do label.frame.size.height to get the height of the label with that amount of text in it.
Upvotes: 0