Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload collection view data when user comes back to view controller

Im trying to reload the data every time the view loads but it is not work. code snippet bellow:

override func viewDidLoad() {
    super.viewDidLoad()
    // Register cell classes
    self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    self.collectionView!.reloadData()
}

but it doesn't work.


2 Answers

The view did load method is only called when the view is instantiated. It appears that it is not being triggered because your transitions are not deinstantiating the collection view cell. (you might be coming back from a pop over, for example)

To force the reload of the data you could try and put that same line of code under view will appear, which is triggered every time the view is about to be presented to the user.

Try doing:

override func viewWillAppear() {
    super.viewWillAppear()
    self.collectionView.reloadData()
}

The order normally goes, viewDidLoad, viewWillAppear and then viewDidAppear.

the above code should fix it. let me know if it doesn't.

like image 87
Usernumbernine Avatar answered Feb 21 '26 05:02

Usernumbernine


Try this

override func viewWillAppear() {
    super.viewWillAppear()
    self.collectionView!.reloadData()
}

This will reload your collection view every time your view controller appears. Also,you donot need to write reloadData() in viewDidLoad()

like image 21
Nishant Avatar answered Feb 21 '26 06:02

Nishant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!