I have a ViewController(VCA) with a TableView inside. From this ViewController it is possibile to call another ViewController (VCB). In this second VC it is possibile add an item to the plist used to populate the TableView in VCA. The problem is that when I save the new item and dismiss the VCB, I can't reload the TableView in VCA.
I have found a lot of examples:
How can you reload a ViewController after dismissing a modally presented view controller in Swift?
How to call reload table view after you call dismissViewController in swift?
How to reload tableview from another view controller in swift
Update the data of a TableViewController after add item
Update the first view after dismissing Popover
Table view is not getting updated after dismissing the popover?
after reading i tried with this code:
**IN VCB**
import UIKit
protocol AddItemDelegateProtocol {
func didAddItem()
}
class VCB: UIViewController {
var delegate : AddItemDelegateProtocol?
...
}
@IBAction func saveButton(_ sender: Any) {
....
self.delegate?.didAddItem()
dismiss(animated: true, completion: nil)
}
**In VCA**
class VCA: UIViewController, UITableViewDelegate, UITableViewDataSource, AddItemDelegateProtocol {
let addItemVC = VCB()
...
override func viewDidLoad() {
super.viewDidLoad()
addItemVC.delegate = self
...
}
func didAddItem() {
self.tableView.reloadData()
}
but this doesn't work. I don't understand where I'm wrong. Could you help me?
EDIT: my Solution I solved in this way:
I've created a singleton in which I declare:
class DataManager {
static let shared = DataManager()
var firstVC = VCA()
.....
}
then, in viewDidLoad of VCA:
DataManager.shared.firstVC = self
now, in the saveButton of VCB, i can call:
@IBAction func saveButton(_ sender: Any) {
........
DataManager.shared.firstVC.tableView.reloadData()
dismiss(animated: true, completion: nil)
}
You can access the presenting ViewController (presentingViewController) property and use it to reload the table view when the view will disappear. When you dismiss the SecondViewController, the tableview of the FirstViewController will reload.
reloadData() Reloads the rows and sections of the table view.
you can do this in two way :-
1)
Do One thing in VCA
VCA
override func viewWillAppear(_ animated: Bool){
tableView.reloadData()
}
If this does not work out then try this.
2) create an instance of VCA in VCB and whenever you move from VCA to VCB pass the value of VCA to the instance of VCB and from there reload the table.
VCB
var instanceOfVCA:VCA! // Create an instance of VCA in VCB
func saveButton(){
instanceOfVCA.tableView.reloadData() // reload the table of VCA from the instance
dismiss(animated: true, completion: nil)
}
VCA
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
VCB.instanceOfVCA = self // Pass the value of VCA in instance of VCB while navigating through segue
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With