什么定义了 UITableViewCell 中 Collection View Cell 的大小?

Posted

技术标签:

【中文标题】什么定义了 UITableViewCell 中 Collection View Cell 的大小?【英文标题】:What defines a size of CollectionViewCell inside a TableViewCell? 【发布时间】:2019-06-01 11:44:45 【问题描述】:

我正在实现UITableView,其中包含UICollectionView。当然我的UITableViewCell有一个UICollectionView,但问题是我不知道UICollectionViewCell的高度怎么配置。我试图设置高度限制以在我的UICollectionViewCell 中查看,但它不影响。玩size的方法有很多种:

句柄大小为UITableViewCell 将高度约束设置为UICollectionViewUITableViewCell UICollectionViewDelegateFlowLayout的使用方法 设置高度限制以查看UICollectionViewCell内部(我的方法)

最后一种方式最适合我,但我想知道为什么它不起作用。这里是UICollectionView的配置:

lazy var booksCollectionView: UICollectionView = 
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    var booksCollectionView = UICollectionView(frame: contentView.bounds, collectionViewLayout: layout)
    booksCollectionView.backgroundColor = .clear
    booksCollectionView.translatesAutoresizingMaskIntoConstraints = false
    return booksCollectionView
()

约束:

booksCollectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    booksCollectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    booksCollectionView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    booksCollectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true

UICollectionView 内的单元格仅包含 UIView

bookView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    bookView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    bookView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    bookView.heightAnchor.constraint(equalToConstant: 440).isActive = true 

更改bookView 的高度完全没有影响。为什么会这样?我应该如何处理UICollectionViewCell 的高度?

【问题讨论】:

【参考方案1】:

符合protocol:UICollectionViewDelegateFlowLayout,实现如下方法: collectionView(_:layout:sizeForItemAt:)

【讨论】:

当我将高度约束设置为 UICollectionView 时调用此方法。但在上面的代码中,我没有设置它。如果不设置高度约束,则不会调用此方法,因此 UICollectionView 中没有单元格。问题是为什么会发生这种情况?在 UICollectionView 的单元格中定义高度的最佳方法是什么? 您不必为使用委托方法设置高度约束。如果您确认协议:UICollectionViewDelegateFlowLayout,代码将调用此方法,不管是什么

以上是关于什么定义了 UITableViewCell 中 Collection View Cell 的大小?的主要内容,如果未能解决你的问题,请参考以下文章

Objective c - 为自定义 UITableViewCell 的按钮处理按钮触摸事件的最佳实践

编辑单元格时自定义 UITableViewCell 反向缩进

如何在 UITableViewCell 中垂直居中对齐 UIButton? (目标 C)

自定义 UITableViewCell 阴影消失

UITableViewCell 选择在目标 c 中不起作用

自定义 UITableViewCell 不显示内容