UICollectionview重用现有单元格

时间:2016-07-19 12:48:02

标签: ios swift2 uicollectionview ios9 uicollectionviewcell

我想用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()

}

1 个答案:

答案 0 :(得分:0)

我认为它可以正确使用,请仔细检查?但我建议设置选定/取消选择单元格样式的方法,您可以覆盖UICollectionViewCell的选定属性。

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()
}