UICollectionview 重用现有单元格

UICollectionview Reuse Existing cell

我想生成包含 100 个单元格的集合视图,但不应在每次滚动时都重新分配,但在我的代码中它总是新创建单元格。

任何人都可以帮助我避免这个问题,请在下面找到我的代码,

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return colorArray.count        
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let colleCell: colorCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! colorCell

    colleCell.bgColor.backgroundColor = UIColor(red: colorArray[indexPath.row].valueForKey("Red") as! CGFloat/255, green: colorArray[indexPath.row].valueForKey("Green") as! CGFloat/255, blue: colorArray[indexPath.row].valueForKey("Blue") as! CGFloat/255, alpha: 1.0)

    return colleCell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    let cell:colorCell = collectionView.cellForItemAtIndexPath(indexPath) as! colorCell

    cell.layer.borderWidth = 2.0
    cell.layer.borderColor = UIColor.whiteColor().CGColor

    selectedColor = indexPath.row

    sampleColorView.backgroundColor = UIColor(red: colorArray[indexPath.row].valueForKey("Red") as! CGFloat/255, green: colorArray[indexPath.row].valueForKey("Green") as! CGFloat/255, blue: colorArray[indexPath.row].valueForKey("Blue") as! CGFloat/255, alpha: 1.0)

    self.view.backgroundColor = UIColor(red: colorArray[indexPath.row].valueForKey("Red") as! CGFloat/255, green: colorArray[indexPath.row].valueForKey("Green") as! CGFloat/255, blue: colorArray[indexPath.row].valueForKey("Blue") as! CGFloat/255, alpha: 0.7)

    sampleColorView.layer.cornerRadius = 75
}



func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath)
{
    let cell:colorCell = collectionView.cellForItemAtIndexPath(indexPath) as! colorCell

    selectedIndex = -1;

    cell.layer.borderWidth = 0.0
    cell.layer.borderColor = UIColor.grayColor().CGColor

    self.view.backgroundColor = UIColor.grayColor()

}

我认为它的重复使用是正确的,请仔细检查一下?但是我建议设置selected/deselected单元格样式的方法,你可以覆盖UICollectionViewCell的selected属性。

class ColorCell : UICollectionViewCell{
    override var selected: Bool{
        didSet {
            layer.borderWidth = selected ? 2 : 0
            layer.borderColor = selected ? UIColor.whiteColor().CGColor : UIColor.grayColor().CGColor
        }
    /* your code */
}

和 UICollectionViewDelegate 实现:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
   selectedColor = indexPath.row
   sampleColorView.backgroundColor = /*Color*/
   view.backgroundColor = /*Color*/
   sampleColorView.layer.cornerRadius = 75
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    selectedIndex = -1;
    self.view.backgroundColor = UIColor.grayColor()
}