Referencing a UICollectionViewCell which is out of bounds

Viewed 216

I have a collectionView with two cells. Each cell fits the size of the screen.
In the first cell I have some buttons.
When I tap a button, the collectionView scrolls to the second cell and depending on which button I tapped, the second cell should show a different view.

This code is to reference the second cell when I tap on a button:

if let cell = collectionView.cellForItem(at: secondIndexPath) as? SecondCell {

        // change the view of the cell
         print("Does not execute code")
}

I guess cellForItem(at: IndexPath) is nil because the cell is out of bounds.
But how can I fix this?

1 Answers

This

let cell = collectionView.cellForItem(at: secondIndexPath)

returns nil when the cell at the specified secondIndexPathisn't visible , you need to alter the model , and it will be reflected to the cell when it's showed again , sine it's cell 2 then

let cellModel = arr[1]  // cell 2 of 0 based indexing 
cellModel.someProperty = ///
Related