Reputation: 1436
I have been working working with collectionViews
and TableViews
to understand how they work but this is a little confusing. I have a collection view hooked up to a ViewController
together with the delegate and datasource set to itself. But on trying to use the didSelectItemAtIndexPath, nothing happens. The collection is displayed perfectly too so the datasource functions are working well.
This is my code:
@IBOutlet weak var timeCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
//Register the Cell
let nib = UINib(nibName: "DurationSelectionCollectionViewCell", bundle:nil)
self.timeCollectionView.registerNib(nib, forCellWithReuseIdentifier: "DurationSelectionCollectionViewCell")
timeCollectionView.delegate = self
timeCollectionView.dataSource = self
....
}
//Selecting an item and highlighting it.
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
timeCollectionView.cellForItemAtIndexPath(indexPath)?.backgroundColor = UIColor.grayColor()
}
Upvotes: 1
Views: 1639
Reputation: 1891
I tested this and it worked as long as your collectionview delegate and datasource are connected. Your problem is that you call timeCollectionView, where you want to call the generic collectionView variable that's given to you in the didSelectItemAtIndexPath declaration. I highlighted it in bold below:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCustomCollectionViewCell
cell.backgroundColor = UIColor.grayColor()
}
Upvotes: 1
Reputation: 814
If didSelectItemAtIndexPathItem:
doesn't get invoked, make sure you have delegate
and dataSource
set properly to your view controller.
Upvotes: 1
Reputation: 864
If you want to change the background color on selecting the item in collection view, you should subclass your UICollectionViewCell
and override highlighted
property.
class DurationSelectionCollectionViewCell: UICollectionViewCell {
override var highlighted: Bool {
didSet {
contentView.backgroundColor = highlighted ? .grayColor() : nil
}
}
}
Upvotes: 0