我有以下 UICollectionView
,它由 Array
填充,NSManagedObject
类型为 Categories
问题是当一个 Cell
被选中时,滚动功能无法正常工作。在 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()
}
}
最佳答案
您不想调用 cellForItemAtIndexPath
并在 didSelectItemAtIndexPath
或 didDeselectItemAtIndexPath
委托(delegate)方法中配置单元格。
此外,您不应从 cellForItemAtIndexPath
方法中调用 selectItemAtIndexPath
和 deselectItemAtIndexPath
。
相反,只需在您的选择/取消选择回调中跟踪和切换所选类别的状态,然后除了在 cellForItemAtIndexPath
中设置您的单元格的外观之外不要做任何其他事情。
正如评论者所指出的,单元格是重复使用的,所以请坚持使用委托(delegate)回调的简单方式,你应该会有更好的运气。
如果您需要刷新单元格的外观,请依靠在滚动时调用的 cellForItemAtIndexPath
并使用 reloadData
和 reloadItemsAtIndexPaths
Collection View 方法,如果你需要强制更新。
关于ios - 在 UICollectionView 中滚动会选择错误的单元格 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27363186/