How to dynamically change the height of a UITableView Cell containing a UICollectionView cell in Swift?

前端 未结 1 1856
攒了一身酷
攒了一身酷 2021-01-27 16:30

Currently, I have embedded a UICollectionViewCell in a UITableViewCell within one of the sections of my UITableView. I know how to dynamic

相关标签:
1条回答
  • 2021-01-27 16:43

    I am using these type of cells in my code, Not performing excellent performance wise(as affecting scrolling smoothness) but will let you achieve required design.

    1. Use CollectionView inside tableViewCell with Vertical ScrollDirection and fixed width(I mean not dynamic in nature). This will put overflowing cells in vertical direction after filling horizontal direction.
    2. Take out NSLayoutConstraint from xib(if you are using that) of collectionViewHeight. We will use it in later part.
    3. set UITableViewAutomaticDimension in tableView in heightForRowAtIndexPath method.
    4. And finally set cell's collectionViewHeight while returning cell in cellForRowAtIndexPath method using constraint that we took out in step 2.

    Here I am attaching some code that may will help:

    UITableView Part:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: xyzTableViewCell.self), for: indexPath) as! xyzTableViewCell
        cell.collectionViewHeight.constant = (numberOfCells/5) * cell.cellHeight
        return cell
    }
    

    UITableViewCell Part:

    @IBOutlet fileprivate weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint
    

    And you will need to reload that particular tableViewCell and reload collectionView inside this tableViewCell so that height function of tableView will be called and height of that tableViewCell will be refreshed, and to handle focused condition of that tableViewCell(when tableViewCell is in focus), I am saying this because if it's not in focus(or say cache, there is difference between them though) then cellForRowAtIndexPath method will be called on scrolling(when this cell is going to come in focus) then tableViewCell height will already be taken care of.

    Hope this will help to achieve required functionality.

    0 讨论(0)
提交回复
热议问题