ios - UITableViewCell 无法根据它包含的动态 CollectionView 调整高度

标签 ios swift uitableview uicollectionview

那么让我从解释 View 层次结构开始。 我使用的是普通的 UITableView,在 UITableViewCell 内部有一个高度动态的 collectionView。

我如何在 UITableView 的 willDisplay 单元格中为 UICollectionView 设置数据源和委托(delegate):

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if indexPath.section == 0 {

        guard let collectionCell = cell as? movieListingTableViewCell else { return }

        collectionCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
        collectionCell.selectionStyle = .none
    }
}

collectionView 有顶部、底部、前导、尾随和高度约束。

Constraints

然后我使用高度约束并将其设置为 collectionView 高度,就像在 UITableView 单元格子类中一样,

override func layoutSubviews() {

    timingCollectionHeight.constant = timingCollection.collectionViewLayout.collectionViewContentSize.height
}

发生的事情是我的单元格没有正确显示,因为有空格。例如,如果有一个 UITableView 单元格具有一个高度较大的 collectionView,则其他 UITableView 单元格也会以某种方式使用相同的高度。滚动表格后,单元格正确显示。

最佳答案

Swift 示例

首先,在 tableViewCell 类中获取 collectionViewHeightConstraint 的导出,如下所示:-

@IBOutlet weak var collectionViewHeight: NSLayoutConstraint!

然后在 ViewController 类的 viewDidLoad() 方法中添加以下代码以实现 tableViewCell 的动态高度:-

myTableView.estimatedRowHeight = 100;  // Default tableViewCell height
myTableView.rowHeight = UITableViewAutomaticDimension;

然后在您的 tableView cellForRowAtindexPath 委托(delegate)中添加以下代码以根据 CollectionView 高度更新 tableView Cell 的高度:-

cell.frame = tableView.bounds;  // cell of myTableView
cell.layoutIfNeeded()
cell.myCollectionView.reloadData()
cell.collectionViewHeight.constant = cell.myCollectionView.collectionViewLayout.collectionViewContentSize.height;

希望这对您有所帮助。 快乐编码:)

关于ios - UITableViewCell 无法根据它包含的动态 CollectionView 调整高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986188/

相关文章:

ios - Delphi - 为 IOS、MacOsx 和 Windows 编写应用程序?

ios - 从 UicollectionView Controller 传递数据时出现问题

swift - 如何使用 OpaquePointer 调用 DSP 函数?

swift - 你们都可以在集合中找到一个类型的第一个实例,并将该实例作为具体类型返回吗?

ios - 获取 SIGABRT 错误

android - 在没有应用程序的情况下测试 firebase 云消息传递

ios - 在自定义单元格 Swift 中保存 uibutton 状态

ios - 如何在 Objective-C 中使用局部变量作为 tableView 的数据源

ios - Swift 4 UIActivityIndi​​catorView 不以 UITableView 为中心

ios - method_exchangeImplementations 导致 EXC_BAD_ACCESS 错误