2

I am basing the question as a branch of this question

The autosize on ViewCells works perfect. But when I reload my CollectionView, the height return 1.

Code as follows.

extension SaleViewController: CollectionViewFlowLayoutDelegate{
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        guard let flowLayout = self.myCollectionView.collectionViewLayout as? CustomLayout else {
            return
        }
        flowLayout.invalidateLayout()
    }

    func height(at indexPath: IndexPath) -> CGFloat {
        guard let cell = self.myCollectionView.cellForItem(at: indexPath) else {
            return 1
        }
        cell.layoutIfNeeded()
        //get calculated cell height
        return cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
    }
}

What is missing or what else should I reconsider to keep my autoheight?

Thanks in advance.

Amg91
  • 165
  • 8
  • 25
  • 1
    So, from this piece of code, it seems like it returns 1 because it can't find a cell at the indexPath you passed. I suggest to put a breakpoint on the `return 1` line and figure out why there is no cell for this indexPath – Tal Cohen Nov 25 '18 at 11:38
  • Maybe you'll have to do `self.myCollectionView.reloadData()` in order for the data to reload before accessing the height. Another thing you could try to do is set the height in the `func cellForItem(at: IndexPath) -> UICollectionViewCell?` function. Another thing to check is to see if you've got the datasource properly connected by implementing `UICollectionViewDataSource` and having `self.datasource = self` in the initializer. – Bram Nov 25 '18 at 20:00
  • please post Code of your CustomLayout – Bhavesh.iosDev Nov 27 '18 at 05:30

1 Answers1

1

Check your CustomLayout there will be cache that store layoutAttribute for your cell.ex : private var cache: [IndexPath : UICollectionViewLayoutAttributes] = [:]

you have to Clear this Cache before reloading

guard let flowLayout = self.myCollectionView.collectionViewLayout as? CustomLayout else {
            return
        }

flowLayout.cache.removeAll()
flowLayout.delegate = self
CollectionView.reloadData()
Erhan Demirci
  • 4,173
  • 4
  • 36
  • 44
Bhavesh.iosDev
  • 924
  • 9
  • 27