Reputation: 1
I want to load the function checkStatus() (which is part of my ViewController1) from my ViewController 2 before the Navigation Controller pops back to the ViewController1. Unfortunately, when calling the function, the app crashes as soon as it loads and I am really frustrated becaue I do not know what I did wrong.
The ViewControllers are embeded in a Navigation Controller.
Code in ViewController1:
func checkStatus(){
/* setting Label texts (Outlets) to a specific value but it is
irrelevant as the compiler does not even get to
this point. The program crashes as soon as the function is called (tried it with prints).*/
Code in ViewController2:
@IBAction func didTapBack(_ sender: UIButton){
// first the function is animating something inside the VC2
ViewController1().checkStatus() // function gets called here
self.navigationController?.popToRootViewController(animated: false)
}
I am grateful for any kind of help.
Upvotes: 0
Views: 192
Reputation: 171
You can use Delegate Pattern to call a function in your case.
ViewController code:
import UIKit
class ViewController: UIViewController, SecondViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func gotoSecondVC(_ sender: UIButton) {
let secondVC = self.storyboard?.instantiateViewController(identifier: "SecondViewController") as! SecondViewController
secondVC.delegate = self
self.navigationController?.pushViewController(secondVC, animated: true)
}
func checkStatus() {
print("\(#function) called...")
}
}
SecondViewController code:
import UIKit
protocol SecondViewControllerDelegate: class {
func checkStatus()
}
class SecondViewController: UIViewController {
weak var delegate: SecondViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func backButtonTapped(_ sender: UIButton) {
delegate?.checkStatus()
self.navigationController?.popViewController(animated: true)
}
}
Upvotes: 1