我正在使用仅允许单个选择的UICollectionView。我当前面临的问题是,即使按了其他选项卡/按钮以选择到另一个视图控制器,仍将保留突出显示的单元格。我想做的是,当我单击显示另一个视图控制器的其他选项卡时,突出显示的单元格将自动取消突出显示。
以下是我的代码:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.allowsMultipleSelection = false
collectionView.allowsSelection = true
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 2.0
cell?.layer.borderColor = UIColor.blue.cgColor
if previouslySelected != nil{
if let previousCell = collectionView.cellForItem(at: previouslySelected!){
previousCell.layer.borderWidth = 0
previousCell.layer.borderColor = .none
}
}
}
override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
collectionView.allowsMultipleSelection = false
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 0
cell?.layer.borderColor = .none
if previouslySelected != nil{
if let previousCell = collectionView.cellForItem(at: previouslySelected!){
previousCell.layer.borderWidth = 0
previousCell.layer.borderColor = .none
}
}
}
编辑:我注意到在按下next并选择其他单元格之后,选定的单元格会更改,但是上一个单元格仍会突出显示(尽管现在不再选择)。关于如何删除未选中的单元格的突出显示的任何想法?
答案 0 :(得分:0)
只分享我如何解决它:
在class CollectionViewController: UICollectionViewController
中声明
var currentlySelected: Int?
var previouslySelected: IndexPath?
下一步,在cellForItemAt函数中,
if currentlySelected != nil && currentlySelected == indexPath.row
{
uploadPostButton.isEnabled = true
cell.layer.borderColor = UIColor.blue.cgColor
cell.layer.borderWidth = 2.0
}
else
{
cell.layer.borderColor = .none
cell.layer.borderWidth = 0
}
也在didSelectItemAt
collectionView.allowsMultipleSelection = false
if previouslySelected != nil{
if let cell = collectionView.cellForItem(at: previouslySelected!){
cell.layer.borderColor = .none
cell.layer.borderWidth = 0
}
}
currentlySelected = indexPath.row
previouslySelected = indexPath
// For reload the selected cell
self.collectionView.reloadItems(at: [indexPath])//this is to "refresh" the selection
所以,这确实达到了我想要的目的,但是我敢肯定,我想学习一种更清洁/更好的方式!