CollectionView when declaring non-reusable cell error "Unexpectedly found while unwrapping an Optional value"

0

I'm implementing a function with collectionView to show me a number of cells.

I have the problem that if the cell declared it as reusable "dequeueReusableCell" when doing vertical scrolling the cells that disappear when returning to show some images of buttons are exchanged for other cells.

I think I saw a code somewhere that this was solved by differentiating each cell with its tag and then showing them according to an order. Another solution was not making the cells reusable.

I wanted to fix it by not reusing cells with cellForItem(at: indexPath) like this:

cell = collectionView.cellForItem(at: indexPath) as! MyCell

but when I am running the program and I have to show the cells it is cut showing the following error:

  

"Fatal error: Unexpectedly found nil while unwrapping an Optional   value "

What is the error?

    
asked by Popularfan 12.06.2018 в 17:21
source

1 answer

1

You should see how you have implemented the cellForRowAtIndexPath method. I think that's where you're going to have the problem and if you do not update the data or the data model you have it wrong. Do not try to do something different that is not going to work for you. I give you an example of this method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   //obtienes la celda que vas a reutilizar
   let cell = tableView.dequeueReusableCell(withIdentifier: "MyCellId", for: indexPath) as! MyCell
   //tienes que obtener lo que quieres mostrar en esta celda
   let item = loQueSeaDeDondeSeaParaElIndexPath: indexPath
   //asignas valores a la celda
   cell.nombre = item.nombre
   cell.edad = item.edad
   .....
   return cell
}

You should also see how you have registered the cell in the table, I'll give you an example:

let nib = UINib(nibName: "MyCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "MyCellId")

I just realized that it is a collectionView, but it would be similar. The method cellForItem (at: indexPath) that you indicate is to get the cell of the indexpath that you pass

    
answered by 12.06.2018 / 19:25
source