Massimo Polimeni
Massimo Polimeni

Reputation: 4906

Can't get the cell reference in collection view when selecting

I have a problem with a simple collection view: in the delegate didSelectItemAtIndexPath I can't get the right reference to the cell. This is my code:

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return categories.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategorySelectionCVCell
    cell.titleLabel.text = categories[indexPath.row]["name"] as? String
    cell.backgroundColor = ConversionUtilities.getUIColorFrom(categories[indexPath.row]["color"] as! String)
    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategorySelectionCVCell
    print("Cell with title: \(cell.titleLabel.text) and background color: \(cell.backgroundColor)")
    collectionView.reloadData()
}

I get always when I select a cell:

Cell with title: Optional("Label") and background color: nil

and I don't know why, it's like the cellForItemAtIndexPath is not working but the same print in cellForItemAtIndexPath give me:

Cell with title: Optional("fruits") and background color: Optional(UIDeviceRGBColorSpace 1 1 0 1)

...and yes, the cell identifier is right is "cell" and I also set up correctly in storyboard. In addition UICollectionViewDataSource and UICollectionViewDelegate are also correctly linked in IB.

Any help?

Upvotes: 2

Views: 1370

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

When you call dequeueReusableCellWithReuseIdentifier method, i.e.

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategorySelectionCVCell

you get an empty cell ready to be reused, not the cell that is currently in your collection view.

Although you can get the cell from the collection view by calling

let cell = collectionView!.cellForItemAtIndexPath(indexPath) as! CategorySelectionCVCell

if all you need is the text from its label it's better to go straight to the model, i.e.

let labelText = categories[indexPath.row]["name"] as? String

Upvotes: 3

Related Questions