Search code examples
iosswiftuicollectionviewtableview

Set collectionView size. (sizeForItemAtIndexPath function is not working) Swift 3


I have a tableView and in every tableViewCell is a collectionView.

I am trying to change the collectionView size with this code:

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

    if collectionView.tag == 2{

        return CGSize(width: 100, height: 100)

    }else if collectionView.tag == 4 {


        return CGSize(width: 222, height: 200)

    }else{


        return CGSize(width: 10, height: 10)
    }

}

The problem is that there is no error but cells do not change sizes

If you need to know something more, just write a comment.

Thank you.


Solution

  • So This is my code right now and it works:

            collectionView.delegate = dataSourceDelegate
            collectionView.dataSource = dataSourceDelegate
            collectionView.tag = row
            collectionView.setContentOffset(collectionView.contentOffset, animated:false)
            collectionView.reloadData()
            collectionView.register(UINib(nibName: "eventsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "eventsCollectionViewCell")
    
    
            if row == 2{
    
    
                let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
                layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                layout.itemSize = CGSize(width: 120, height: 120)
                layout.scrollDirection = .horizontal
    
                collectionView.collectionViewLayout = layout
    
            }else if row == 4 {
    
    
                let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
                layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                layout.itemSize = CGSize(width: 222, height: 200)
                layout.scrollDirection = .horizontal
    
                collectionView.collectionViewLayout = layout
    
            }else{
    
                print("else")
            }