I have two ViewControllers, FirstViewController
and SecondViewController
. Both have an own Swift file, FirstViewController.swift
and
You may use NSNotificationCentre
to accomplish this task.
In viewDidLoad
method of your SecondViewController
class register self as observer to receive notification broadcasts:-
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(showAlert), name: NSNotification.Name(rawValue: "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
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "callForAlert"), object: nil)
}
Don't forget to call removeObserver
in SecondViewController's viewDidUnload
method.
Try this:
SecondViewController().showAlert(self)
In your second view controller
if let text = textField?.text {
dispatch_async(dispatch_get_main_queue(),{
let alert = UIAlertView(title: "Working!", message: "This function was called from FirstViewController!\nTextField says: \(text)", delegate: nil, cancelButtonTitle: "Okay")
alert.show()
})
}
If you want to show alert view to second viewcontroller
from firstview controller
when go to it you can do something like,
self.performSegueWithIdentifier("your segue identifier", sender: self) // or whatever way if you are not using storyboard or segue
let alert = UIAlertView(title: "Working!", message: "This function was called from FirstViewController!", delegate: nil, cancelButtonTitle: "Okay")
alert.show()
If you want to set any variables
of secondviewcontroller
then you need to implement prepareForSegue
method. (if you are using segue).
Second thing you can show alertview in viewDidload
of secondViewController
also.
EDIT: These functions have been revised in swift 3 as follows:
Code in FirstViewController
override function viewDidLoad(){
NotificationCenter.default.addObserver(self, selector: #selector(showAlert), name: NSNotification.Name(rawValue: "showAlert"), object: nil)
}
Code in SecondViewController:
@IBAction func callFunctionInOtherClass(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showAlert"), object: nil)
}