ios - UITableViewCell 中的 UICollectionVIew 如何使用自动布局获取动态高度

标签 ios uitableview autolayout uicollectionviewcell

我知道有一个类似的question ,但我想就我如何尝试实现这一目标提供更多提示,因为原始问题没有提供任何建议。
我有一个 UITableViewCell 作为 contentView 的 subview ,有一个 UICollectionView,我想让单元格高度在 collectionview contentSize 的函数中>, TableView 单元格是 Collection View 委托(delegate)和数据源。
Collection View 应该固定在垂直流中没有滚动的可能性,并且它应该根据单元格行的数量调整其高度。
为此,我尝试使用与常见表​​格 View 单元格相同的技术。我创建了一个假单元格并保留对它的引用,然后在方法 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 中,我将数据提供给单元格应该显示然后询问其高度以获取压缩大小。
类似的东西:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize  size = CGSizeZero;
    NSDictionary * data = self.data[indexPath.row];
    if (data[KEY_CELL_IDENTIFIER] == CellIdentifierPost) {
        NSNumber * cachedHeight = [self.heightCaches objectForKey:[(PostObject*)data[KEY_CELL_DATA] postObjectId]];
        if (cachedHeight) {
            return (CGFloat)[cachedHeight doubleValue];
        }
        [_heightCell configureCellWith:data[KEY_CELL_DATA]];
        size = [_heightCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        [self.heightCaches setObject:@(size.height) forKey:[(PostObject*)data[KEY_CELL_DATA] postObjectId]];
    }
    else if (data[KEY_CELL_IDENTIFIER] == CellIdentifierComment){
        size = (CGSize) {
            .width = NSIntegerMax,
            .height = 160.f
        };
    }
    else {
        size = (CGSize) {
            .width = NSIntegerMax,
            .height = 50.f
        };
    }

    return size.height;
}

此方法对其他单元格非常有效,但对这个单元格无效,结果是一个完全压缩的单元格,高度几乎为零。
问题似乎是由于内部单元格的放置。即使在提供数据后我强制 Collection View 重新加载数据,它似乎永远不会调用 -collectionView:cellForItemAtIndexPath: 发生这种情况可能是因为单元格仍未显示。
有变通办法吗?

最佳答案

我建议您为您的 collectionView 创建一个高度限制。

然后,根据单元格的数量,您可以计算它的高度,最后,您更新该约束并调用 [collectionView setNeedsUpdateConstraints]

关于ios - UITableViewCell 中的 UICollectionVIew 如何使用自动布局获取动态高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182803/

相关文章:

ios - 在 Swift 中使用 xib 创建 UIView

javascript - 移动浏览器 : update element on back button

ios - 顶级应用程序如何几乎同时发送多个 ios 推送通知?

ios - 使用自动布局实现按钮的网格布局

IOS/Objective-C/Autolayout 水平居中四张图片

ios - 制作我自己的容器文件类型

queryForTable 之后 Swift reloadTableView

ios - 不符合 UITableViewDataSource - 解析应用

ios - 组 TableView 标题显示在 admob 横幅上

ios - UIStackView sizeToFit 无法按预期工作