How to get cell atIndex in UICollectionView with swift?
In Swift 4 you can get the cell of CollectionView with:
let indexPath = IndexPath(item: 3, section: 0);
if let cell = myCollectionView .cellForItem(at: indexPath)
{
// do stuff...
}
This is the way to get the cell at a given indexPath:
let cell = collectionView!.cellForItemAtIndexPath(indexPath)
However, you also might want to try:
cell.contentView.backgroundColor = UIColor.blueColor()
NOTE:
Though the above may have worked, I want to encourage you to try a different implementation to achieve the same functionality. Your implementation would require you to have a separate Action# function for each CollectionViewCell, as well as create the indexPath manually in each of those methods, when you could potentially only have one!
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.blackColor()
cell.buttonView.addTarget(self, action: Selector("action"), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
and the function for that one method would be something like:
func action(sender: UIButton!) {
var point : CGPoint = sender.convertPoint(CGPointZero, toView:collectionView)
var indexPath = collectionView!.indexPathForItemAtPoint(point)
let cell = collectionView!.cellForItemAtIndexPath(indexPath)
cell.backgroundColor = UIColor.blueColor()
}
Updated action function for Swift 4.2
@objc func action(sender: Any){
print("tickedOffPressed !")
if let button = sender as? UIButton {
let point: CGPoint = button.convert(.zero, to: collectionView)
if let indexPath = collectionView!.indexPathForItem(at: point) {
let cell = collectionView!.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.blue
}
}
}
Just a suggestion! Happy coding! :)