我有tableview单元格,里面有collectionview单元格,而且它还有collectionview单元格,我如何根据collectionview单元格设置tableview单元格的高度?
尝试将其添加到您的控制器中
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
你的问题含糊不清。
您应该提供一个您想要实现的目标的示例。
假设集合视图单元格有静态高度: 简单,自动布局将是你的朋友。 使用:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
但是,如果您想动态布局表格视图单元格高度:
// You may need to call it when viewDidLayoutSubviews() is called
let height = collectionView.collectionViewLayout.collectionViewContentSize.height
collectionViewHeightConstraint.constant = height
contentView.layoutIfNeeded()
如果您有动态内容,首先您需要遵守
UICollectionViewDelegateFlowLayout
并实施collectionView(_:layout:sizeForItemAt:)
。您还需要定义高度约束并手动更新。
在单元格(或包含集合视图的任何视图)中,定义高度约束。
private lazy var collectionViewHeightContraint: NSLayoutConstraint = {
return self.collectionView.heightAnchor.constraint(equalToConstant: 0)
}()
然后在布局集合视图时使用此约束。
NSLayoutConstraint.activate([
// place other constraints here
collectionViewHeightContraint
])
然后创建另一个函数来更新约束。
func updateHeightConstraint() {
layoutIfNeeded()
collectionViewHeightContraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
collectionView.reloadData()
}
如果您有任何类型的配置方法,请将此方法设为私有并在配置方法中调用它。
例如
func configure(using viewModel: ViewModel) {
titleLabel.text = viewModel.title // Do any UI configuration you need.
updateHeightConstraint()
}
private func updateHeightConstraint() {
layoutIfNeeded()
collectionViewHeightContraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
collectionView.reloadData()
}
最后,您需要在拥有表视图的更高级别中重写 viewDidLayoutSubviews 。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Tell table view to update its layout if needed.
tableView.beginUpdates()
tableView.endUpdates()
}