arthur丶Top
整理自己发现的学习知识点,好记性不如烂笔头。

在做tableView的时候,我们有时候需要根据cell的高度动态来调整,最近在网上看到一段代码不错,跟大家Share一下。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

类中获取cell的高度:
[objc] view plain copy
 
  1. CGSize boundSize = CGSizeMake(216, CGFLOAT_MAX);  
  2. cell.textLabel.text = @"12345678900123456789";  
  3. cell.userInteractionEnabled = NO;  
  4. cell.textLabel.numberOfLines = 0;  
  5. CGSize requiredSize = [cell.textLabel.text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:boundSize lineBreakMode:UILineBreakModeWordWrap];  
  6. CGRect rect = cell.frame;  
  7. rect.size.height = requiredSize.height+5;  
  8. cell.frame = rect;  
这时候获取到了cell的高度,然后在

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

类中改变cell的高度:
[objc] view plain copy
 
  1. UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];  
  2.   
  3. NSLog(@"cell height %f",cell.frame.size.height);  
  4.   
  5. return cell.frame.size.height;  

这样以来cell的高度就根据cell里label的内容自动改变啦。

其主要出发点就是我有一个label,然后我要把这个label展示出来,我根据字体的大小还有行数来获取一个高度,这样cell的高度就有啦

posted on 2016-02-25 11:31  arthur丶Top  阅读(614)  评论(0编辑  收藏  举报