0

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)
}

3 Answers3

3

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   
        }
    }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

You can pass the selected category to the previous view controller using closure

class FirstViewController: UIViewController {   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? SecondViewController {
            secondVC.selectedOption = { selectedOption in
                print(selectedOption)
                //change category title here
            }
        }
    }

}
class SecondViewController: UIViewController {
    var selectedOption: ((String) -> Void)?
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedOption?("Selected Option String")
        navigationController?.popViewController(animated: true)
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
0

Maybe you should pass "Completion handler" when you move to your category selection controller like

(String)->(Void)

and when you pop it, pass your category in this clouser

Ilya Stukalov
  • 101
  • 1
  • 3