如何在iOS中创建具有动态tableview高度的动态tableview单元格 [英] How to create dynamic tableview cell with dynamic tableview height in iOS

查看:232
本文介绍了如何在iOS中创建具有动态tableview高度的动态tableview单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据内容增加tableview单元格和tableview高度。
假设tableview包含2条记录,他的第1个单元格高度为100,第2个单元格高度为25,则tableview高度应为100 + 25 = 125。
如何实现这一功能?

I want to increase tableview cell and tableview height based on content. Suppose tableview contain 2 record and his 1st cell height is 100 and 2nd cell height is 25 then tableview height should be 100+25=125. How to achieve this functionality?

提前致谢。

推荐答案

你绝对可以这样做,


  1. 首先确保你的单元格子视图的约束必须设置为从上到下为了计算单元格所需的高度。

  1. First make sure your constraint of cells subView must set to top to bottom in order to calculate the height required for the cell.

确保您的委托设置如下

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
      return 44;
} 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}


  • 设置tableView的高度约束并设置该约束的出口。

  • Set height constraint of your tableView and make outlet of that constraint.

    将以下方法添加到您想要动态调整tableView大小的类中。

    Add below method to your class where you want to resize your tableView dynamically.

    - (void)adjustHeightOfTableview
    {
    
        CGFloat height = self.tableView.contentSize.height;
       //CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
    
       /* 
         Here you have to take care of two things, if there is only    tableView on the screen then you have to see is your tableView going below screen using maxHeight and your screen height,
         Or you can add your tableView inside scrollView so that your tableView can increase its height as much it requires based on the number of cell (with different height based on content) it has to display.
      */
    
      // now set the height constraint accordingly
      self.constraintHeightTableView.constant = height;
    
     //If you want to increase tableView height with animation you can do that as below.
    
     [UIView animateWithDuration:0.5 animations:^{
           [self.view layoutIfNeeded];
     }];
    }
    


  • 准备好表格的dataSource时调用此方法,并将方法调用为

  • Call this method when you are ready with the dataSource for the table, and call the method as

    dispatch_async(dispatch_get_main_queue(), ^{
    
        [self.tableView reloadData];
    
        //In my case i had to call this method after some delay, because (i think) it will allow tableView to reload completely and then calculate the height required for itself. (This might be a workaround, but it worked for me)
        [self performSelector:@selector(adjustHeightOfTableview) withObject:nil afterDelay:0.3];
    });
    


  • 这篇关于如何在iOS中创建具有动态tableview高度的动态tableview单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆