【发布时间】:2018-01-04 12:01:50
【问题描述】:
我正在尝试实现此功能:在我的应用程序中,如果我在 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 属性。我将不胜感激。
【问题讨论】:
-
为 CollectionView 添加委托 "collectionView.delegate = self"
-
@Ragul 谢谢!但它已经完成了:我有另一个类,它符合 UICollectionViewDataSource 和 UICollectionViewDelegate 协议,我声明了这个类的一个实例作为我的 UICollectionView 的委托和数据源。此外,第一步工作正常:单击任何单元格后,边框变为蓝色(这意味着代表团工作正常),但是当我单击其他单元格时,它们的边框也变为蓝色,但前一个的边框单元格仍然是蓝色的(我想要透明的)。
-
只需为每个选择重新加载collectionView
-
@Ragul 在哪些方法中?据我了解,didSelectItemAt 和 DidDeselectItemAt 正在重新加载我的收藏(它们都包含 collectionView.reloadData())
-
为什么会被调用?你在同一个运行循环中显式地重新加载整个集合视图......当iOS知道它将重新加载整个集合时,它并不愚蠢地执行deselect一行 -无论如何都在同一个循环中查看。
标签: ios swift uicollectionview