2

I need to access to the particular cell and change its content dynamically on didSelectAt indexPath

func collectionView(_ collectionView: UICollectionView, 
    didSelectItemAt indexPath: IndexPath) {
        if collectionView == self.trendHeaderView{
            print(indexPath.row)
            // Needs to access cell and change the 
            // content of cell i.e label text inside cell ??
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
shubh14896
  • 156
  • 1
  • 12

2 Answers2

0

I need to access to the particular cell

No, you don't. You should never meddle with a cell's contents directly. You need to access the data (the "model") that the collection view's data source is using. And you can easily do that, because you have the indexPath. Change the data, and reload the collection view so that it picks up the changes and displays them.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Consider a case I have a view inside cell and label, and I have to change the nested view background then how can I do that ?? – shubh14896 Sep 26 '17 at 05:36
  • Do just what I said in my answer. Make the info about what the "nested view background" should be part of the _data_ (the model). In other words, encode all info needed into the model, and then have your `cellForItemAt:` take care of the configuration based on that info. That is what it _means_ to have a data source. No other approach can possibly work, not least because cells are reused in different item slots. – matt Sep 26 '17 at 05:47
0

You can't change the cell's content directly in didSelectItemAt. As you can see, in UICollectionView cell is reused by calling dequeReusableCell.

So I think, it's good to make model for that. and change the model content in didSelectItemAt. and Please call reloadData to redraw collectionview.

Lead Developer
  • 1,146
  • 10
  • 26