UITableViewCell 动态高度内的非滚动 UICollectionView

Non-Scrolling UICollectionView inside UITableViewCell Dynamic Height

我在 UITableViewCell 中添加了 UICollectionView,为此我创建了 XIB 文件。检查下图:

您可以在上图中看到所有视图的层次结构和约束。

Note: I have disable collection view vertical and horizontal scrolling because I want to increase UITableViewCell height dynamically. So I have taken collection view's height's constraint's outlet and changing it programatically based on item available in collection view.

集合视图的项目大小如果固定,宽度与集合视图成比例,高度为 30

我已经使用以下代码在我的 table 视图中注册了这个 xib。

self.tblSubCategory.register(SubCategoryTVC.Nib(), forCellReuseIdentifier: "SubCategoryTVC")

这是我的SubCategoryTVC代码:

class SubCategoryTVC: UITableViewCell {

    @IBOutlet weak var categoryView                 : UIView!
    @IBOutlet weak var categoryImageView            : UIView!
    @IBOutlet weak var imgCategory                  : UIImageView!
    @IBOutlet weak var lblCategoryName              : UILabel!

    @IBOutlet weak var cvSubcategory                : UICollectionView!

    // MARK: Constrains's Outlet
    @IBOutlet weak var const_cvSubcategory_height   : NSLayoutConstraint!


    class func Nib() -> UINib {
        return UINib(nibName: "SubCategoryTVC", bundle: nil)
    }

    func setCollectionView(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        self.cvSubcategory.delegate = dataSourceDelegate
        self.cvSubcategory.dataSource = dataSourceDelegate
        self.cvSubcategory.tag = row
        self.cvSubcategory.reloadData()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

UITableViewDataSource:

extension SignupSecondStepVC: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    //------------------------------------------------------------------------------

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "SubCategoryTVC", for: indexPath) as! SubCategoryTVC

        cell.lblCategoryName.text = "Category \(indexPath.row)"

        cell.cvSubcategory.register(SubCategoryCVC.Nib(), forCellWithReuseIdentifier: "SubCategoryCVC")

        return cell
    }
}

UITableViewDelegate:

extension SignupSecondStepVC: UITableViewDelegate {

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

        guard let subCategoryCell = cell as? SubCategoryTVC else { return }

        // This line of code set dataSource and delegate to `SignupSecondStepVC` instead of `SubCategoryTVC`
        subCategoryCell.setCollectionView(dataSourceDelegate: self, forRow: indexPath.row)

        subCategoryCell.cvSubcategory.setNeedsLayout()

        // This will change height of collection view based on item available.
        subCategoryCell.const_cvSubcategory_height.constant = 30 * 5

        subCategoryCell.cvSubcategory.setNeedsLayout()
        subCategoryCell.contentView.layoutIfNeeded()
    }

    //------------------------------------------------------------------------------

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    //------------------------------------------------------------------------------

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

以上代码为UITableView,请见以下UICollectionView

代码

UICollectionViewDataSource:

extension SignupSecondStepVC: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    //------------------------------------------------------------------------------

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubCategoryCVC", for: indexPath) as! SubCategoryCVC

        cell.btnSelection.setCornerRadius(radius: cell.btnSelection.frame.size.height / 2)
        cell.lblSubCategoryName.text = "SubCategory \(indexPath.row)"

        return cell
    }
}

UICollectionViewDelegateFlowLayout:

extension SignupSecondStepVC: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = collectionView.frame.size.width
        return CGSize(width: width, height: 30)
    }
}

完成所有这些事情后,我遇到了单元格加载和 UI 的问题。当我 运行 应用程序和加载数据第一次遇到 UI 问题并且数据加载不正确时。请观看以下视频,以便您了解我的实际问题。

Issue Video

请帮我解决这个问题。

您需要将 collectionView delegate/datasource 与 TableViewCell 绑定,并且需要在 tableViewcell 中使用以下函数。确保关闭 CollectionView 滚动。

override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

    self.layoutIfNeeded()
    let contentSize = self.cvSubcategory.collectionViewLayout.collectionViewContentSize
    if self.cvSubcategory.numberOfItems(inSection: 0) < 4 {
        return CGSize(width: contentSize.width, height: 120) // Static height if colview is not fitted properly.
    }

    return CGSize(width: contentSize.width, height: contentSize.height + 20) // 20 is the margin of the collectinview with top and bottom
}

您的项目示例解决方案:https://github.com/thedahiyaboy/DynamicCollectionApp


为了将来的目的,您可以从此 post 获取参考: