Label text in UICollectionViewCell not updating

2019-05-20 22:27发布

问题:

I'm trying to change the text of a UILabel in a UICollectionViewCell after the UICollectionViewCell has loaded, when tapping a button. But the label doesn't update on the screen. The console shows that the text property of the label is updated, but it seems the label isn't redrawn with the new text.

Is this a known problem with UICollectionViewCells? Some kind of caching issue, perhaps? Do I need to reload the cell, or the entire collection view for the update to show?

回答1:

Because the cell is already loaded, no change in cell will happen until it's reloaded, so you can either reload the entire collection view [self.collectionView reloadData];

Or just one/multiple cell(s) that got affected with that change of data

[self.collectionView reloadItemsAtIndexPaths: indexpathArray];

But make sure that you change the data properly before reloading the cells



回答2:

I had a similar situation where a UILabel in the collectionView cell was updating fine. Then after making some modifications to the storyboard, the UILabel would not change when updating the value programmatically. As noted in the initial question the value stayed the default value even though the debug terminal showed that the connected UILabel attribute text was being updated.

Here is how I resolved the issue. In the storyboard,

  1. Deleted the referencing outlet for the UILabel (in the "Show the connections Inspector")
  2. Deleted the UILabel from the storyboard
  3. Re-added the UILabel
  4. Reconnected the referencing outlet to the swift file code attribute

And somehow, everything started working fine again.

As a side note: The swift 3.1 versions of Radwa's answer are:

collectionView.reloadItems(at: [indexPath]) // single cell in the collection view
collectionView.reloadData() // entire collection view