简体   繁体   中英

UICollectionView Enlarge cell on selection

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.

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

Pay attention to this phrase: did Deselect ItemAtIndexPath.

did Select ItemAtIndexPath is a way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM