1 class uiviewcontroller ios swift
我有两个ViewControllers,FirstViewController
和SecondViewController
.两者都有自己的Swift文件,FirstViewController.swift
和SecondViewController.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
录制时调用UIButton
in FirstViewController
.
我已经花了很多个夜晚才找到解决方案但没有工作.有谁知道该怎么做才能达到这个目标?
我在这里上传了一个示例Xcode项目:CallFuntionInOtherClassX | filedropper.com
PS:当然,我可以发布一些代码并解释我得到的错误,但我认为这是不合理的,因为我真的不知道该怎么做.
您可以使用它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)
不要忘记调用removeObserver
SecondViewController的viewDidUnload
方法.