简体   繁体   English

UICollectionView选择时放大单元格

[英]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. 在调试时,我发现选择滞后于我上述方式在didDeselectItemAtIndexPath中,但不确定原因。

The problem is that you are're using func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) . 问题是您正在使用func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath)

Pay attention to this phrase: did Deselect ItemAtIndexPath. 请注意以下短语: 取消选择 ItemAtIndexPath。

did Select ItemAtIndexPath is a way to go. Select ItemAtIndexPath是一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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