设置 UITableView Cell 高度(包含动态 UICollectionView)

Posted

技术标签:

【中文标题】设置 UITableView Cell 高度(包含动态 UICollectionView)【英文标题】:Set UITableView Cell height (contain dynamic UICollectionView) 【发布时间】:2018-06-23 18:12:01 【问题描述】:

我的目标: 每个 UITableView 单元包含 1 个 UIColletionViewController(动态项数

问题: UITableView 'HeightForRow 的委托,在 UIColletionViewController 完成加载他的视图 + 高度之前调用。

结果: UITableView 'HeightForRow = 0

如何正确设置 UITableView "HeightForRow" 委托? UIColletionViewController 的内容高度尚未加载

结果应该如下图所示:

已尝试:

- (void)viewDidLoad 
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = 300.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;


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

   //not working well
    return UITableViewAutomaticDimension;

    //also tried this:
    ResultsTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    Object * object = [_array objectAtIndex:indexPath.section];
    [cell setCellObject:object]; //this is build the cell ui
    return cell.collection.rect.size.height;

【问题讨论】:

【参考方案1】:

返回“内容大小”(而不是 view.size)

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

    //1. get the cell (by identifier)
    ResultsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ResultsTableViewCell"];

    //2. build cell ui
    Object * object = [_array objectAtIndex:indexPath.section];
    [cell buildCell:object];

    //3. return content size
    return cell.collection.collectionView.contentSize.height;

【讨论】:

以上是关于设置 UITableView Cell 高度(包含动态 UICollectionView)的主要内容,如果未能解决你的问题,请参考以下文章