【发布时间】:2017-12-21 13:34:41
【问题描述】:
我正在使用 didSelectItemAt 和 didDeselectItemAt 来选择 collectionViewCell。我想选择单元格并将边框设为蓝色(如果已选中)并取消选择“选定”单元格并将边框设为默认值。但我的问题是 didDeselectItemAt 被交替调用。当我点击任何单元格然后调用 didSelectItemAt 并且如果我点击任何其他单元格然后调用 didDeselectItemAt。我猜这不应该发生。仅当我点击已选择的单元格时才应调用 didDeselectItemAt。如果我错了,请纠正我。我已经提到了这个UICollectionView - didDeselectItemAtIndexPath not called if cell is selected1,但是对我有用:(
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
let cell = collectionView.cellForItem(at: indexPath) as! MomentDetailCell
let moment = self.arrOfMoments[indexPath.row] as! MomentModel
cell.toggleSelection(moment: moment)
self.arrOfDeletingImgs.append(moment)
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
{
let cell : MomentDetailCell = self.collectionViewImages.cellForItem(at: indexPath) as! MomentDetailCell
let moment = self.arrOfMoments[indexPath.row] as! MomentModel
cell.toggleSelection(moment: moment)
self.arrOfDeletingImgs.remove(at: (find(objecToFind: moment))!)
}
// 这也是我在课堂上使用的代码。我还在 viewdidload 中设置了allowMultipleSelection true
extension MomentDetailViewController : UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 75, height: 75)
}
}
//这是我的customCell代码
func toggleSelection( moment : MomentModel)
{
if (isSelected)
{
moment.isSelected = true
self.layer.borderWidth = 3
self.layer.borderColor = Constant.APP_BLUE_COLOR.cgColor
}
else
{
moment.isSelected = false
self.layer.borderWidth = 1
self.layer.borderColor = UIColor.red.cgColor
}
}
【问题讨论】:
-
我猜当您点击第二个单元格时会调用 didselect 方法,因此首先会被取消选择。您再次点击第一个并保持选中状态,您是否检查过它是否转到其他单元格?您需要将选定的索引状态保存在某处。
标签: ios objective-c swift3 uicollectionviewcell