H.N. H.N. - 9 days ago 5
Swift Question

Going from one ViewController to another ViewController and updating

Now I have 3 Viewcontrollers like this:

Home Viewcontroller = VC1.
Viewcontroller2 = VC2 --> has a table view with cells on it.
Viewcontroller3 = VC3 --> allows me to edit each cell in VC2 or delete.


I am using navigation controller between Viewcontrollers, to get the nice "back" button :)

Lets say I am in VC1, I press a button and I go to VC2.
Now let's say I have 4 cells.
I press cell number 2 and I go to VC3, where I can edit what I have in the cell or even delete it.
This is all working ok (tested it).

Let's say I want to delete that cell. I have a button on VC3 and I use it and I delete the cell (this is tested and also working ok).

Now when I do this I push into VC2 again like this:

let viewController = storyboard?.instantiateViewController(withIdentifier: "VC2") as! VC2!
self.navigationController?.pushViewController(viewController!, animated: true)


The problem is that when I do this I go to VC2 but I doesn't reload my table has it should (the erased cell it's still there).

To fix this I tried adding some code in VC2, in the viewDidLoad:

self.tableView.reloadData()


Now I managed to do it work. I mean when I delete a cell from VC3 I am pushed to VC2 and the cell it's not there. However If I press the back button it takes me to the previous cell that I have deleted,,, If the cell doesn't exist anymore I don''t want it to take me there. I want it to take me to the VC1 (home).

How can I make this work?

Perhaps I should do this in another way and not pushing like that?

Answer

Practically you are doing wrong, when delete / edit operation done on VC3 and you want to come back on VC2, why you are doing pushViewController , you have to apply popViewController.

You have to apply self.navigationController?.popViewController(animated: true) coming back to VC2 from VC3.

Remove

let viewController = storyboard?.instantiateViewController(withIdentifier: "VC2") as! VC2!
self.navigationController?.pushViewController(viewController!, animated: true)

Add

self.navigationController?.popViewController(animated: true)

Also

Put reloadData() method for table view in viewWillAppear. like below code.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.tableView.reloadData()

}

Some reference material to read about UINavigationController.

https://developer.apple.com/reference/uikit/uinavigationcontroller

Comments