I have a collection view with two custom cells one is for grid and one is for list, i want to be able to touch cells and select them as as if want to delete or share them , all i want for now to be able to select and deselct them, ill post my code below the result is when i touch one cell all cells are selected! here is the code:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if isGridSelected {
let cell:cell2_Class = collectionView.dequeueReusableCellWithReuseIdentifier("cell2", forIndexPath: indexPath) as! cell2_Class
cell.listImage.image = imageArray[indexPath.row]
if flag == true {
cell.layer.borderColor = UIColor.blueColor().CGColor
cell.layer.borderWidth = 3
cancelButton.hidden = false
} else {
cell.layer.borderColor = UIColor.clearColor().CGColor
cancelButton.hidden = true
}
return cell
} else {
let cell:PhotoCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! PhotoCollectionCell
if flag == true {
cell.layer.borderColor = UIColor.blueColor().CGColor
cell.layer.borderWidth = 3
cancelButton.hidden = false
} else {
cell.layer.borderColor = UIColor.clearColor().CGColor
cancelButton.hidden = true
}
cell.imageView.image = imageArray[indexPath.row]
cell.NameLabel.text = namelabel[indexPath.row]
cell.ModifiedLbl.text = modfLabel[indexPath.row]
return cell
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
if cell!.selected == true {
flag = true
} else {
flag = false
}
self.collectionView.reloadData()
}
Based on Aerows solution Swift 4.2
Subclass of
collectionViewCell
in
UICollectionViewDelegate
And very important, on your
viewDidLoad()
don't forget to allow your collectionView multiple selectionApple documentation - allowsMultipleSelection
In
PhotoCollectionCell
andcell2_Class
(or in a commonsuperclass
) simply override this methodThen you don't have to deal with the actual
selection/highlighting
in yourdelegate
ordataSource
.Make sure to have your
collectionView
has the propertyallowsSelection
toYES
.If you want
multiple selection
then also setallowsMultipleSelection
toYES
and implement the following method in yourdelegate
Swift Solution
Subclass of
collectionViewCell
in
UICollectionViewDelegate
: