bla0009 bla0009 - 4 months ago 88
Swift Question

Swift disable hidden property for UIImageView in Cell in UICollectionView

I am using Swift 2 with XCode 7 beta. I am rendering UICollectionView with Cells that have image and label in it. Image should be hidden at the time of viewLoad.

This is my code:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell
cell.contactName.text = contactsNames[indexPath.row]
cell.selectedIcon.hidden = true

return cell
}

// selection of the item
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell
cell.selectedIcon.hidden = false
}


I have also tried during loading to put in first collectionView method
cell.selectedIcon.hidden = true
, which showed the items. But still interaction didn't work (when I click on the item, it didn't show).

Can you advice how to solve this? Thanks!

Answer

First of all read this about the dequeueReusableCellWithReuseIdentifier method:

Call this method from your data source object when asked to provide a new cell for the collection view. This method dequeues an existing cell if one is available or creates a new one based on the class or nib file you previously registered.

To access to one specific cell there are severals options you can use but in your specific case I think the method cellForItemAtIndexPath(_:)(this method is not the same you use to set the initial values for the cells, like you put above) is the best choice, like in the following way:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
   let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ContactCell
   cell.selectedIcon.hidden = false
}

I hope this help you.