I have the following UICollectionView
which is populated by an Array
with NSManagedObject
of type Categories
The problem is that when a Cell
is selected scrolling does not function correctly. When scrolling through the UICollectionView
other cells get selected, and deselected. Strange behaviour. I think this is because of the indexPath that is set incorrectly after scrolling? Anyway, I have been struggling with this for a couple of hours, and cannot seem to grasp it. Hopefully someone can point me in the right direction!
The fetchedCategory gets compared to the category to check if it is already selected and if they are the same the colors are inverted.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("CategorySelectionCollectionCell", forIndexPath: indexPath) as CategoryCollectionViewCell
if fetchedCategories[indexPath.row] == category {
cell.categoryLabel?.text = fetchedCategories[indexPath.row].name
cell.categoryLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = fetchedCategories[indexPath.row].iconColor as? UIColor
collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.None)
} else {
cell.categoryLabel?.text = fetchedCategories[indexPath.row].name
cell.categoryLabel?.textColor = fetchedCategories[indexPath.row].iconColor as UIColor
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
}
return cell
}
func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) {
var cell = collectionView.cellForItemAtIndexPath(indexPath) as CategoryCollectionViewCell
cell.categoryLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = fetchedCategories[indexPath.row].iconColor as? UIColor
category = fetchedCategories[indexPath.row]
}
func collectionView(collectionView: UICollectionView!, didDeselectItemAtIndexPath indexPath: NSIndexPath!) {
if var cell = collectionView.cellForItemAtIndexPath(indexPath) as? CategoryCollectionViewCell {
cell.categoryLabel?.text = fetchedCategories[indexPath.row].name
cell.categoryLabel?.textColor = fetchedCategories[indexPath.row].iconColor as UIColor
cell.backgroundColor = UIColor.whiteColor()
}
}