从其他ViewController调用函数 [英] Call function from other ViewController
问题描述
我有两个ViewControllers, FirstViewController
和 SecondViewController
。两者都有自己的Swift文件, FirstViewController.swift
和 SecondViewController.swift
。
I have two ViewControllers, FirstViewController
and SecondViewController
. Both have an own Swift file, FirstViewController.swift
and SecondViewController.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()
}
}
我希望能够在 SecondViewController中调用
在 func showAlert()
FirstViewController
中点击 UIButton
时。
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?
我在这里上传了一个示例Xcode项目: CallFuntionInOtherClassX | filedropper.com
I uploaded a sample Xcode project here: CallFuntionInOtherClassX | filedropper.com
PS:当然,我可以发布一些代码并解释我得到的错误,但我认为这是不合理的,因为我真的不知道该怎么做。
推荐答案
你可以使用 NSNotificationCentre
完成此任务。
You may use NSNotificationCentre
to accomplish this task.
在 viewDidLoad
的方法> SecondViewController
类注册self作为观察者来接收通知广播: -
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)
}
并且在 FirstViewController
的按钮操作方法中,您应该通过以下方式触发通知: -
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)
}
不要忘记在SecondViewController的 viewDidUnload $ c $中调用
removeObserver
c>方法。
Don't forget to call removeObserver
in SecondViewController's viewDidUnload
method.
这篇关于从其他ViewController调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!