【发布时间】:2014-12-08 17:10:35
【问题描述】:
我有以下UICollectionView,它由Array 填充,NSManagedObject 类型为Categories
The problem is that when a Cell is selected scrolling does not function correctly.当滚动UICollectionView 时,其他单元格会被选中和取消选中。奇怪的行为。我认为这是因为滚动后设置错误的 indexPath?无论如何,我已经为此苦苦挣扎了几个小时,似乎无法掌握它。希望有人能指出我正确的方向!
将 fetchedCategory 与类别进行比较以检查它是否已被选中,如果它们相同,则颜色会反转。
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()
}
}
【问题讨论】:
-
这没什么奇怪的,你得到这个结果是因为你不了解单元重用。您不应该在 didSelectRowAtIndexPath 中设置单元格属性,因为当该单元格被重用时,它将与这些更改一起出现,但现在在集合视图中的不同位置。相反,您应该更改模型中的属性,在 cellForRowAtIndexPath 中检查该属性,并在 if-else 子句中适当地设置您的 UI。在此站点上进行一些搜索以进行单元重用;你应该会找到很多答案。
-
你能发一个例子吗(swift 3)@rdelmar
标签: ios swift uicollectionview