Search code examples
swifttableviewcollectionview

How do we return a value of collection view that is inside of tableview cell?


I have a table view cell that has a collection view inside of it, and i wanted to make a static method i can use from outside the class to get the value but i can not do that what is an alternative way to return size of this collection view inside the table view cell

What I did is i stored a property with collection view height but couldn't return it in func


Solution

  • There are many ways to achieve this. One of the simplest ways it to use protocols.

    In your CollectionViewCell but outside of your class, define protocol:

    protocol CollectionViewCellDelegate: class {
        func sizeOfCollectionView(size: CGSize)
    }
    

    In your CollectionViewCell class; define this protocol as a weak variable

    weak var delegate: CollectionViewCellDelegate?
    

    In your CollectionViewCell class; where you have the correct size; return it to any observers of this delegate using the following method:

    self.delegate?.sizeOfCollectionView(size: bounds.size)
    

    Now this delegate receives sizeOfCollectionView calls and it's parent can observe it.

    For example:

    In your parent class:

    cell.delegate = self
    

    After doing this try to build the project and Xcode will tell you that your class doesn't have the delegate implemented. You can then define the delegate as follows:

     extension ParentClass: CollectionViewDelegate {
        func sizeOfCollectionView(size: CGSize) {
           // You will receive size here
        }
     }
    

    Here I'm also adding a medium tutorial for a more detailed explanation on this.

    Hope these help!