【问题标题】:What defines a size of CollectionViewCell inside a TableViewCell?什么定义了 UITableViewCell 中 Collection View Cell 的大小?
【发布时间】: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 的高度?

【问题讨论】:

    标签: ios uitableview uicollectionview


    【解决方案1】:

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

    【讨论】:

    • 当我将高度约束设置为 UICollectionView 时调用此方法。但在上面的代码中,我没有设置它。如果不设置高度约束,则不会调用此方法,因此 UICollectionView 中没有单元格。问题是为什么会发生这种情况?在 UICollectionView 的单元格中定义高度的最佳方法是什么?
    • 您不必为使用委托方法设置高度约束。如果您确认协议:UICollectionViewDelegateFlowLayout,代码将调用此方法,不管是什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多