UICollectionView Enlarge cell on selection

2019-05-27 11:39发布

问题:

I want to resize a particular cell in my collection view when it is selected. I found how to do so from previous posts, but ran into a problem. I found while debugging that the selection lagged behind by one, but I am not sure why.

For example, if I select one cell by tapping it, nothing happens. If I select another cell after, then the first cell I selected is enlarged. If I select a third cell, the second is enlarged. And so on.

This is how I implemented it, and only once cell is ever enlarged at the same time like I want:

var selectedIndexPath: NSIndexPath!
func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if selectedIndexPath != nil { //We know that we have to enlarge at least one cell
        if indexPath == selectedIndexPath {
            return CGSize(width: self.gallery.frame.size.width, height: self.gallery.frame.size.width)
        }
        else {
            return CGSize(width: self.gallery.frame.size.width/3.0, height: self.gallery.frame.size.width/3.0)
        }
    }
    else {
        return CGSize(width: self.gallery.frame.size.width/3.0, height: self.gallery.frame.size.width/3.0)
    }
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    if selectedIndexPath != nil && selectedIndexPath == indexPath
    {
        selectedIndexPath = nil //Trigger large cell set back to normal
    }
    else {
        selectedIndexPath = indexPath //User selected cell at this index
    }
    collectionView.reloadData()
}

I found while debugging that the selection lagged in didDeselectItemAtIndexPath in the way I described above, but am not sure why.

回答1:

The problem is that you are're using func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath).

Pay attention to this phrase: didDeselectItemAtIndexPath.

didSelectItemAtIndexPath is a way to go.