I want to generate collectionview with 100 number of cells, But it should not to be reallocate at every time of scrolling, But in my code its always creating cells newly.
any one help me to avoid this issue, please find my code below,
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()
}
I think it's reused correctly, plz double check? But I suggest the way to set selected/deselected cell's style, you can override selected property of 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 */
}
and UICollectionViewDelegate implementation:
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()
}