How to make UILabel / UITableViewCell to have a dynamic height

来源:互联网 发布:天天动听mac版下载 编辑:程序博客网 时间:2024/06/18 10:28

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.

How to make UILabel / UITableViewCell to have a dynamic height

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:

  1. - (CGFloat)tableView:(UITableView *)tableView  
  2.            heightForRowAtIndexPath:(NSIndexPath *)indexPath;  

If you want UITableViewCell to have a dynmic height,you'll need to calculate the height of text block and return the resultin the method I mentioned above.

There are four NSString methods that can do the calculations:

  1. - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size;  
  2. - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size  
  3.           lineBreakMode:(UILineBreakMode)lineBreakMode;  
  4. - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width  
  5.           lineBreakMode:(UILineBreakMode)lineBreakMode;  
  6. - (CGSize)sizeWithFont:(UIFont *)font  
  7.           minFontSize:(CGFloat)minFontSize  
  8.           actualFontSize:(CGFloat *)actualFontSize  
  9.           forWidth:(CGFloat)width  
  10.           lineBreakMode:(UILineBreakMode)lineBreakMode;  

To calculate the exact height of a text block, you'll need tospecify a large CGSize and those methods will return you exact size,here's an example:

  1. CGSize aSize;  
  2.   
  3. aSize = [aString sizeWithFont:[UIFont systemFontOfSize:14]  
  4.                  constrainedToSize:CGSizeMake(300.0, 1000.0)  
  5.                  lineBreakMode:UILineBreakModeTailTruncation];  

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 inthe model class when setting the string and storing the height in themodel 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.

原创粉丝点击