I recently found out, that even though according to the documentation sizeToFit on a UILabel will take into account the numberOfLines property, it simply doesn't.
You have seen variable heights of UITableViewCell in iPhone applications like App Store, Address Book, SMS and so on. These applications have a UITableView as main part, but each cell in the table has a variable height according to text amount it holds.
With UITableView it is quite different if you're coming from a HTML world, as UITableView cannot generate a dynamic height automatically , you'll need to calculate the height yourself before you set the delegate.
After you created a UITableView , you will need to set a delegate and a datasource . There is a UITableViewDelegate method to tell UITableView how tall a cell would be:
If you want UITableViewCell to have a dynmic height, you'll need to calculate the height of text block and return the result in the method I mentioned above.
There are four NSString methods that can do the calculations:
To calculate the exact height of a text block, you'll need to specify a large CGSize and those methods will return you exact size, here's an example:
Then you can get the height by accessing aSize.height .
What I'm doing most of the time is to call one of those methods in the model class when setting the string and storing the height in the model class, so you can use the correct height right away.
Now to size the UILabel and/or UITableViewCell you just need to set the frame property of UILabel and/or UITableViewCell .