user7684436
user7684436

Reputation: 717

Get next cell in UIcollectionView in Swift

I need to get the next cell inside cellForItem within a collection view so that I can update a view object. When I try the following below it doesn't work. I've also tried indexPathForVisibleItems passing in indexPath.row + 1 and the produces an index out of range error.

    let index = IndexPath(row: indexPath.row + 1, section: indexPath.section)
            if let nextCell = collectionView.cellForItem(at: index) as! MKRCell {
                nextCell.setupWaitView(time: timeToWait)
                nextCell.waitViewHeightConstraint.constant = 80
                nextCell.waitView.alpha = 1
                nextCell.waitView.isHidden = false
            }

Is this possible to achieve or will I need to do this via another way?

Thanks

Upvotes: 0

Views: 2155

Answers (2)

Salman Ghumsani
Salman Ghumsani

Reputation: 3657

No, it is not possible to get the cell object before initialization in cellForItemAt but here you can receive the call before displaying the cell from UICollectionViewDelegate

func collectionView(_ collectionView: UICollectionView,willDisplay cell: UICollectionViewCell,forItemAt indexPath: IndexPath) {
     if let myCell = cell as? MKRCell {

     }
}

AND

If you want to set up the cell you have to setup view in the UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

}

Upvotes: 2

Rafał Sroka
Rafał Sroka

Reputation: 40028

You should update the cell in:

func collectionView(_ collectionView: UICollectionView, 
    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

Remember to modify only the cell you'll be returning from this method. Other cells might not have exist at that moment.

Alternatively you can keep a weak reference to the cell and update it when needed.

Upvotes: 1

Related Questions