David David - 3 months ago 12
iOS Question

Xcode, Swift; Call function from other ViewController

I'm developing an iOS app with Xcode and Swift.

I have two ViewControllers,

FirstViewController
and
SecondViewController
. Both have an own Swift file,
FirstViewController.swift
and
SecondViewController.swift
.

FirstViewController.swift
contains:

class FirstViewController: UIViewController {
@IBAction func callFunctionInOtherClass(sender: AnyObject) {
// Call "func showAlert" in SecondViewController when clicking the UIButton in FirstViewController
}
}


SecondViewController.swift
contains:

class SecondViewController: UIViewController {

@IBOutlet weak var textField: UITextField!

func showAlert(sender: AnyObject) {
let alert = UIAlertView(title: "Working!", message: "This function was called from FirstViewController!\nTextField says: \(textField.text!)", delegate: nil, cancelButtonTitle: "Okay")
alert.show()
}
}


I want to be able to call the
func showAlert()
in
SecondViewController
when taping on the
UIButton
in
FirstViewController
.

I've already spent many nights to find a solution but none worked. Does anybody know what to do to reach this goal?

I uploaded a sample Xcode project here: CallFuntionInOtherClassX | filedropper.com

P.S.: Of cause, I could post some code and explain what error I get, but I think it's not reasonable because I really don't know how to do that.

Answer

You should use NSNotificationCentre to accomplish this task.

In viewDidLoad method of your SecondViewController class register self as observer to receive notification broadcasts:-

override func viewDidLoad() {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showAlert), name: "callForAlert", object: nil)
}

and in FirstViewController's button action method you should fire the notification by writing :-

@IBAction func callFunctionInOtherClass(sender: AnyObject) {
    //Call "func showAlert" in SecondViewController when clicking the UIButton in FirstViewController

    NSNotificationCenter.defaultCenter().postNotificationName("callForAlert", object: nil)
}

Don't forget to call removeObserver in SecondViewController's viewDidUnload method.