How to refresh a viewController when a tab bar is pressed?

Hi,


I have 5 tab bars, when I press one of them I want the viewController's data to be refreshed.


I'm using this code:


func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 4 {
           self.collectionView.reloadData()
          viewDidLoad()
           
          
        }
    }


every time I'm pressing the tab bar for the specific viewController,

the view and the data inside the collection view cell is refreshed,

but the collectionView triples the cells.


is there another way to refresh the data?


thank you

You should never ever call viewDidLoad or viewDidAppear yourself. Only UIKit should ever call those. If there’s some setup code currently in there that needs to run again when you refresh, then put that in a separate function and call it from both places.


As for “collectionView triples the cells” - as KMT is suggesting, you’re going to have to do some debugging. Set breakpoints in your data source methods. See what your code is returning for the number of cells when asked. If you have 3x the number of items in your data model, then you’ll have to look at the code that sets that up.

Only when I call viewDidLoad it's triple the cells.


what should I do?

It worked for me if I wanted to go from one viewController to another when I did that code:


let tabVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavigationTab") as! UITabBarController
        tabVC.selectedIndex = 4
       
        self.present(tabVC, animated: true, completion: nil)
        self.loadView()
self.view.setNeedsLayout()

but if I want to press a tab it doesnt work.

Again. Never ever call any of the view lifecycle methods such as loadView yourself. UIKit will load the view if and when it needs to.


I would suggest doing your reload in viewWillAppear of your collection view’s view controller. I believe that should be triggered when the user switches tabs.

I've tried doing that viewWillappear, but it seems that collectionView.reloadData() doesnt work inside that code.


Is there a way someone can help me and look in my code what is wrong?

or suggest me a better way to reload my data in collection view cells when I press the tab?

How to refresh a viewController when a tab bar is pressed?
 
 
Q