从其他ViewController调用函数

我有两个ViewControllers, FirstViewControllerSecondViewController 。 两者都有自己的Swift文件, FirstViewController.swiftSecondViewController.swift

FirstViewController.swift包含:

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

SecondViewController.swift包含:

 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() } } 

我希望能够在SecondViewControllerFirstViewController UIButton时调用func showAlert()func showAlert()

我已经花了很多个晚上才找到解决方案,但都没有效果。 有人知道该怎么做才能达到这个目标吗?

我在这里上传了一个示例Xcode项目: CallFuntionInOtherClassX | filedropper.com

PS:当然,我可以发布一些代码并解释我得到的错误,但我认为这是不合理的,因为我真的不知道该怎么做。

您可以使用NSNotificationCentre来完成此任务。

在您的SecondViewController类的viewDidLoad方法中,注册self作为观察者来接收通知广播: –

 override func viewDidLoad() { NotificationCenter.default.addObserver(self, selector: #selector(showAlert), name: NSNotification.Name(rawValue: "callForAlert"), object: nil) } 

FirstViewController的按钮操作方法中,您应该通过以下方式触发通知: –

 @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) } 

不要忘记在SecondViewController的viewDidUnload方法中调用removeObserver

编辑:这些function已在swift 3中进行了如下修改:

FirstViewController中的代码

  override function viewDidLoad(){ NotificationCenter.default.addObserver(self, selector: #selector(showAlert), name: NSNotification.Name(rawValue: "showAlert"), object: nil) } 

SecondViewController中的代码:

 @IBAction func callFunctionInOtherClass(sender: AnyObject) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showAlert"), object: nil) } 

如果你想从second viewcontroller视图firstview controllersecond viewcontroller视图firstview controller显示警报视图,那么你可以做类似的事情,

  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() 

如果要设置secondviewcontroller任何variables ,则需要实现prepareForSegue方法。 (如果你使用segue)。

第二件事你也可以在viewDidloadsecondViewController显示alertview。

尝试这个:

 SecondViewController().showAlert(self) 

在你的第二个视图控制器

  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() }) }