简体   繁体   中英

Updating a single cell in swift UICollectionview

I have a simple hangman game that I wanted to make more elegant using a UIcollectionview but getting a single cell to update is causing even more of my hair to drop out!!

The logic of the code works, if I try to insert or delete a cell the app crashes and the indexPath variable prints out happily but the UIcollectionview cell refuses to update.

I used Xcode's storyboard to create the view and it has a named outlet and prototype cell, the view populates happily but will not change, what am I doing wrong? Any help would be appreciated.

let indexPath1 = IndexPath(item: item!, section: 0)
reloadCollectionView(indexPath: indexPath1 as NSIndexPath?)

then I call:

func reloadCollectionView(indexPath:NSIndexPath?) {
    print("reload indexPath item: \(indexPath?.item) and section: \(indexPath?.section)")
    if (indexPath != nil){
        let cell = collectionOutlet.cellForItem(at: indexPath as! IndexPath) as! ElementsCollectionViewCell

        let section = indexPath?.section

        if section == 0 {

                    cell.letterLabel.text = self.lettersArray0[(indexPath?.item)!]
                    collectionOutlet.reloadItems(at: [indexPath as! IndexPath])

                    print(" Cell text: \(cell.letterLabel.text ?? "NOWT")")
               //collectionOutlet.reloadData()
                    print("Index \(indexPath)")

}

The cellForItemAt method is what updates your cells. The proper way to get a cell to update is to update the model, then reload the collection view, which will call cellForItemAt and redraw your cell based on the model.

In your case it looks like your model is self.lettersArray0 so make sure it has been updated before you call reload.

You can reload your cells using any of the following methods:

    collectionView?.reloadData()
    collectionView?.reloadItems(at: )
    collectionView?.reloadSections(sections:)

If you want to update just one cell, and not reload the whole collection view, you can do:

collectionOutlet.performBatchUpdates({
    collectionOutlet.reloadItems(at: [indexPath])
}){
    // optional closure
    print(“finished updating cell”)
}

performBatchUpdates Documentation reloadItems Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM