Search code examples
iosswiftrealm

How I can transfer data between controllers when returning to the last screen? Swift


In the application, I am asked to select a category, when I click, I move to the next screen from the tableView, and when I click on the desired category, it should be saved and return to the previous controller, where instead of "select a category" my chosen category will be.

I using by this method navigationController?.popViewController(animated: true), which brings me back to the last screen. As I understand it, prepare is not called, but since I know exactly where I'm going, I can, in the method from which I call pop ..., get access to the controller I am switching to and pass it the necessary properties? But how?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  let currentCell = categories[indexPath.row]
    /?
    /?
  navigationController?.popViewController(animated: true)
}

Solution

  • When you go to the select screen do

    let vc = ///
    vc.delegate = self
    // push
    

    then inside didASelectRowAt

    class CategoryViewController:UIViewController {
     weak var delegate:PreviousVC?
     ////
    }
    
    delegate?.sendData(someData)
    navigationController?.popViewController(animated: true)
    

    Another option inside didASelectRowAt to

    // access previous vc
    let previousVC = self.navigationController!.viewControllers[self.navigationController!.viewControllers.count - 2] as! PreviousVc
    previousVC.sendData(someData)
    // pop here
    

    Edit: inside the firstVC

         override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let secondVC = segue.destination as? SecondViewController {
              secondVC.delegate = self   
            }
        }