那么让我从解释 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 有顶部、底部、前导、尾随和高度约束。
然后我使用高度约束并将其设置为 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/