Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Reload a View Controller

I need to refresh a view controller when a certain button is tapped. Simply activating viewDidLoad() does not seem to be working for what I need to do. However, when I leave the view controller then come back to it, it seems to work perfectly?

How can I refresh/reload a view controller as if I have left it then come back to it without ever actually leaving it?

like image 638
Matt Spoon Avatar asked Jul 03 '15 13:07

Matt Spoon


People also ask

How to refresh a view controller in Swift?

In my view, the best way to "reload the ViewController" is simply to remove the object from memory and create an entirely new one (as is done above). This also removes viewModels, etc. from memory that were instantiated in the VC (assuming no circular reference issues).

How do I refresh a tab bar in Swift?

extension Notification.Name { static let refreshAllTabs = Notification.Name("RefreshAllTabs") } class MainTabBarController: UITabBarController, UITabBarControllerDelegate { override func viewDidLoad() { super. viewDidLoad() NotificationCenter. default. addObserver(forName: .

What is viewDidLoad in Swift?

This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView() method.


2 Answers

Whatever code you are writing in viewDidLoad, Add that in viewWillappear(). This will solve your problem.

like image 50
iAnurag Avatar answered Oct 06 '22 19:10

iAnurag


You shouldn't call viewDidLoad method manually, Instead if you want to reload any data or any UI, you can use this:

override func viewDidLoad() {     super.viewDidLoad();      let myButton = UIButton()      // When user touch myButton, we're going to call loadData method     myButton.addTarget(self, action: #selector(self.loadData), forControlEvents: .TouchUpInside)      // Load the data     self.loadData(); }  func loadData() {     // code to load data from network, and refresh the interface     tableView.reloadData() } 

Whenever you want to reload the data and refresh the interface, you can call self.loadData()

like image 22
Edward Anthony Avatar answered Oct 06 '22 20:10

Edward Anthony