从其他ViewController调用函数
我有两个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 } }
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
中FirstViewController
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 controller
向second 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)。
第二件事你也可以在viewDidload
的secondViewController
显示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() }) }