[转] iOS TableViewCell 动态调整高度

原文: http://blog.csdn.net/crayondeng/article/details/8899577

最近遇到了一个cell高度变化的问题,在找解决办法的时候,参考了这篇文章,觉得不错

在写sina 微博的显示微博内容时,用到cell进行显示,那么就要考虑到不同微博内容导致的cell高度问题。在微博显示的内容中包括了文字和图片,那么就要计算文字部分的高度和图片部分的高度。这篇博文就记录一下如何处理cell高度的动态调整问题吧!

一、传统的方法

在 tableview的delegate的设置高度的方法中进行设置- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath,当然在这个代理方法中需要计算文字的高度以及图片的高度,然后返回。

1、文字(string)高度的处理;

由于文字的长度的不确定的,所以就要根据这个动态的文字长度来计算机显示文字的的高度

  1. #define FONT_SIZE 14.0f  
  2. #define CELL_CONTENT_WIDTH 320.0f  
  3. #define CELL_CONTENT_MARGIN 10.0f  
  4.   
  5. NSString *string = @"要显示的文字内容";  
  6. CGSize size = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAXFLOAT);  
  7. CGSize textSize = [string sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];  


以上代码就是计算文字高度。其中size是装载文字的容器,其中的height设置为maxfloat;然后用方法
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
Returns the size of the string if it were rendered with the specified constraints.就可以知道string的size了


2、图片高度的处理;
首先你先要下载到图片,然后CGSize imageViewSize = CGSizeMake(image.size.width,image.size.height);就可以获取到图片的size,就可以对你的 imageview的frame进行设置了,那么也就知道了图片的高度了。

二、非传统方法
在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath代理方法中处理cell的frame的高度,在tableview的delegate的设置高度的方法中调用这个方法,那么就可以 得到设置好的cell高度。(注意到二者方法的执行顺序:heightForRowAtIndexPath这个代理方法是先执行的,后执行 cellForRowAtIndexPath)

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     static NSString *CellIdentifier = @"Cell";  
  4.       
  5.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  6.     if (cell == nil) {  
  7.         //cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];  
  8.         //这个方法已经 Deprecated  
  9.           
  10.         cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];  
  11.           
  12.     }  
  13.     CGRect cellFrame = [cell frame];  
  14.     cellFrame.origin = CGPointMake(0, 0);  
  15.   
  16. //获取cell的高度的处理  
  17.   
  18.     cellFrame.size.height = ***;  
  19.     [cell setFrame:cellFrame];  
  20.     return cell;  
  21.       
  22. }  


稍微解释一下,注意到cell初始化的时候是CGRectZero,然后[cell frame]获取cell的frame,让后就可以对cell的高度进行处理后,setFrame 重新设置cell 的frame了。
接下来就是在heightForRowAtIndexPath这个方法中调用。

    1. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {  
    2.   
    3.     UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];  
    4.     return cell.frame.size.height;  
    5. }

(其实这里又会调用一次cellForRow的cell重绘方法,很耗性能)

原文地址:https://www.cnblogs.com/A--G/p/4552832.html