Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload tableview from another view controller in swift

When I dismiss a modal view controller I want the tableview to update, I am using the form sheet presentation style on iPad so the viewWillAppear and the viewDidAppear methods will not work

like image 730
Suneet Tipirneni Avatar asked Sep 18 '14 20:09

Suneet Tipirneni


2 Answers

You can do this:

In your tableView Controller:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
}
 
@objc func loadList(notification: NSNotification){
    //load data here
    self.tableView.reloadData()
}

Then in the other ViewController :

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
like image 109
Sebastian Avatar answered Oct 20 '22 20:10

Sebastian


Swift 3 version code: In your first view controller:

override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
    }

func loadList(){
        //load data here
        self.tableView.reloadData()
    }

In your second view controller:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
like image 51
mriaz0011 Avatar answered Oct 20 '22 20:10

mriaz0011