0

I have two UIViewControllers and each one has an UITableView. Lets say that when I call from View-A to View-B, I take the cells which are marked in the UITableView in View-B and, after pressing a button I want to return an array with all the data selected from View-B to View-A, dismiss View-B and represent that information in the TableView of View-A. How can I pass that array ? How do I have to reaload the data in View-A to show it after dimissing View-B ?

Any idea? Thank you very much!!

TibiaZ
  • 730
  • 1
  • 8
  • 21

3 Answers3

1
protocol DataPasserDelegate {
   func sendDatatoA(dataArrayFromB : Array<AnyObject>)
}

class ViewB: UIViewController {

var delegate: DataPasserDelegate!

var dataArrayB = Array<AnyObject>()

@IBAction func sendData(sender: Any){
    self.dismiss(animated: true) { 
        self.delegate.sendDatatoA(dataArrayFromB: self.dataArrayB)
    }
 }
}

class ViewA: UIViewController, DataPasserDelegate {

@IBOutlet weak var tableViewA: UITableView!

var dataArrayA = Array<AnyObject>()

//MARK: - DataPasserDelegate
func sendDatatoA(dataArrayFromB: Array<AnyObject>) {
    dataArrayA = dataArrayFromB

    self.tableViewA.reloadData()
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destVC = segue.destination as? ViewB{
        destVC.delegate = self
    }
 }
}
Aadil Ali
  • 351
  • 1
  • 15
0

So you can use prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "segueID") {
        if let controller = segue.destination as? YourVC{
            controller.array = yourArray
            controller.tableView.reloadData()
        }
    }
}
Phyber
  • 1,368
  • 11
  • 25
  • In the line "if let controller == segue.destination as? ListsViewController" it says Variable binding in a condition requires an initilizer. Any idea ? – TibiaZ Jul 28 '17 at 10:40
  • Who did downvoted this and why? I normally pass variables to other VC's like this. What is wrong with this? – J. Doe Jul 28 '17 at 10:51
  • It seems the function is not executed. Shouldn't it be executed when I call my button function (which contains "self.navigationController?.popViewController(animated: true)") in View-B ? – TibiaZ Jul 28 '17 at 11:10
-1

You will need to use delegate for this. For more information on delegates you can go through my blog here.

Mohammad Sadiq
  • 5,070
  • 28
  • 29