AlexVilla147
AlexVilla147

Reputation: 283

how to get the cell at index path.item - 1 in collection view

I want to access the previous cell (index path.item - 1) in my collection view to change some settings there if some conditions are fulfilled in the cell at index path.item

By now I tried this:

        let previousCell = collectionView.cellForItem(at: indexPath - 1)

But it doesn't work because of the - 1 it is downcast from index path to an integer value.

How do I get this cell?

Upvotes: 0

Views: 4828

Answers (2)

Vini App
Vini App

Reputation: 7485

Please check :

let previousCell = collectionView.cellForItem(at: IndexPath(row: indexPath.row-1, section: indexPath.section))

To get cell with identifier :

let prevIndexPath = IndexPath(row: indexPath.row-1, section: indexPath.section)
let previousCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: prevIndexPath)

Upvotes: 5

matt
matt

Reputation: 536009

What does "previous cell" even mean? Do you mean the same section but the previous row? Then construct an index path with a row less than this row.

However, the question itself seems to indicate a total misconception about how table views work. You should not need to "access" any cells at all. Update your model and reload the table (or the relevant cells).

Upvotes: 1

Related Questions