sankalp kasle
sankalp kasle

Reputation: 19

collectionView.cellForItem(at: indexPath) not working properly

i've read made my collectionViewController a delegate of UICollectionViewDelegateFlowLayout, i've registered my cell correctly, collectionView?.register(ActivityCell.self, forCellWithReuseIdentifier: cellId) , I have dequed the cell properly and returned it

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: ActivityCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ActivityCell

        return cell
    }

but whenever i try to retrieve the cell using the indexPath in sizeForItemAtIndexPath function , it doesnt return the activity cell

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let cell: ActivityCell = self.collectionView?.cellForItem(at: indexPath) as? ActivityCell
        {
            let approximatewidthofcell = view.frame.size.width - 50
            let size = CGSize(width: approximatewidthofcell, height: 1000)
            let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15)]

            let estimatedframe = NSString(string: cell.activitylabel.text!).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
            return CGSize(width: view.frame.size.width, height: estimatedframe.height)
        }
        else
         {
            return CGSize(width: view.frame.size.width, height: 200)
        }

    }

The If block is always ignored, whereas the else block is executed everytime, i have no idea what code to manipulate next, please help

Upvotes: 0

Views: 767

Answers (1)

silentBob
silentBob

Reputation: 170

I didn't look at collection views a while, but i think this is an order thing, this method is called before cellForItem . Also, did you assign datasource?

Upvotes: 1

Related Questions