UITableViewCell内部的非滚动UICollectionView动态高度

May*_*mur 2 uitableview ios autolayout uicollectionview swift

我已UICollectionView在内部添加UITableViewCell,为此我创建了XIB文件。检查以下图片:

UITableView Xib

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

注意:因为我想UITableViewCell动态增加高度,所以我禁用了集合视图的垂直和水平滚动。因此,我已经采用了收集视图的高度约束的出口,并根据收集视图中可用的项目以编程方式对其进行了更改。

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

我已使用以下代码在我的表视图中注册了该xib。

self.tblSubCategory.register(SubCategoryTVC.Nib(), forCellReuseIdentifier: "SubCategoryTVC")
Run Code Online (Sandbox Code Playgroud)

这是我的代码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()
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码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
    }
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

完成所有这些操作后,单元格加载和UI出现问题。第一次运行应用程序并加载数据时,出现UI问题,而数据加载不正确。请参阅以下视频,以便您了解我的实际问题。

发行影片

请帮助我解决此问题。

dah*_*boy 6

您需要将您的collectionView委托/数据源与TableViewCell绑定,并需要在tableViewcell中使用以下func。确保关闭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
}
Run Code Online (Sandbox Code Playgroud)

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


为了将来的目的,您可以参考以下文章:TableViewCell Swift中的Dynamic CollectionViewCell