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 course, 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.
You may use
NSNotificationCentre
to accomplish this task.In
viewDidLoad
method of yourSecondViewController
class register self as observer to receive notification broadcasts:-and in
FirstViewController
's button action method you should fire the notification by writing :-Don't forget to call
removeObserver
in SecondViewController'sviewDidUnload
method.Try this:
In your second view controller
Code in FirstViewController
Code in SecondViewController:
If you want to show alert view to
second viewcontroller
fromfirstview controller
when go to it you can do something like,If you want to set any
variables
ofsecondviewcontroller
then you need to implementprepareForSegue
method. (if you are using segue).Second thing you can show alertview in
viewDidload
ofsecondViewController
also.