I have programmed UIBarButtonItem so that it does some action before switching to a previous view. I was wondering how do I get the viewcontroller of that transitioning scene from my UIBarButtonItem? So, scene 1 -> scene 2 (current scene) -> scene 1 (after clicking the UIBarButtonItem button)

I've tried to pass the previous scene variables (that I need) to the current scene to perform action on (sense I don't think the transitioning scene is instantiating a new view, but that doesn't work

    override func viewDidLoad() {
        super.viewDidLoad()
        loadTuple()
        let addButton: UIBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveExercise(_: )))
        self.navigationItem.setRightBarButton(addButton, animated: true)

    }
    @objc func saveExercise(_ sender: UIBarButtonItem) {
        self.addNewTupleToDB(element: self.getNewTuple())
        self.saveData()
        debugPrint("saveExercise")
        self.exerciseVCTableView?.reloadData() // tried to pass the table view from the previous scene to call here
        self.navigationController?.popViewController(animated: true)
        // Want to save reload the table data of the scene this button transitions to
    }```

1 Answers

0
Ankur Lahiry On

You may use delegate pattern for solving this. Delegate pattern is something, to delegate some work to other and return to the work after delegation is done.

Suppose ViewController1 has UIBarButton , goes to ViewController2, some function done and return to ViewController1

let us take a protocol

protocol MyProtocol {
   func myFunction()
}

then in ViewController2 add a delegate method. Assuming in ViewController2, you have to call a method doMyWork and some work will be done here, then you have to pop.

class ViewController2 {
    var delegate : MyProtocol?

    override func viewDidLoad() {
       super.viewDidLoad()
       doMyWork()
    }

    func doMyWork() {
       // my works 
       delegate?.myFunction()
       self.navigationController.popViewController()
    }
}

now the viewController1 have to receive the delegate work has done.

in viewController1, in barButtonItem

class ViewController1 {

    @objc func barButton(_sender : UIBarButton) {
       let viewController = ViewController2()
       viewController.delegate = self 
       self.naviagtionController.pushViewController(viewController, animated : true)
    }

}

now you have to implement protocol method

extension ViewController1 : MyProtocol {
    func myFunction() {
       self.tableView.reloadData()
    }
}