从其他ViewController调用函数

1 class uiviewcontroller ios swift

我有两个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
    }
}
Run Code Online (Sandbox Code Playgroud)

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够func showAlert()SecondViewController录制时调用UIButtonin FirstViewController.

我已经花了很多个夜晚才找到解决方案但没有工作.有谁知道该怎么做才能达到这个目标?

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

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

Pan*_*dav 6

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

viewDidLoad您的SecondViewController类注册自己作为观察者接收通知广播的方法: -

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

并且在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)
}
Run Code Online (Sandbox Code Playgroud)

不要忘记调用removeObserverSecondViewController的viewDidUnload方法.