我正在尝试实现此功能:在我的应用程序中,如果我在 UICollectionView 中选择了一个单元格,则边框会变为蓝色,如果我选择另一个单元格,则应取消选择前一个单元格并且边框应变为透明。我写了一些方法:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ChatCell
/* Set some settings */
if globalSelected[indexPath.item] {
cell.circleView.layer.borderColor = UIColor.blue.cgColor
} else {
cell.circleView.layer.borderColor = UIColor.clear.cgColor
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//Global variable for maintain selection
global.selectedChatPath = indexPath
globalSelected[indexPath.item] = true
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if indexPath != nilPath {
globalSelected[indexPath.item] = false
collectionView.reloadData()
}
}
nilPath 只是 IndexPath(item: -1, section: 0),但它不是没关系,因为甚至没有调用 collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)。我的 CollectionView 有 allowSelection = true 和 allowsMultipleSelection = false 属性。如果有任何帮助,我将不胜感激。
最佳答案
如果应该同时选择单个单元格,我建议将当前选择的索引路径放入实例变量(nil
表示未选择任何内容)
var selectedIndexPath : IndexPath?
在cellForItemAt
中根据实例变量设置颜色
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ChatCell
/* Set some settings */
if let selected = selectedIndexPath, selected == indexPath {
cell.circleView.layer.borderColor = UIColor.blue.cgColor
} else {
cell.circleView.layer.borderColor = UIColor.clear.cgColor
}
return cell
}
在 didSelectItemAt
中,仅重新加载以前和新选择的单元格,并将 selectedIndexPath
设置为新选择的索引路径。这比重新加载整个 Collection View 更有效。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//Global variable for maintain selection
var cellsToReload = [indexPath]
if let selected = selectedIndexPath {
cellsToReload.append(selected)
}
selectedIndexPath = indexPath
collectionView.reloadItems(at: cellsToReload)
}
didDeselectItemAt
仅在您想明确取消选择单元格时才需要。
关于ios - 选择另一个单元格时不会触发 didDeselectItemAt indexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373118/