gpt4 book ai didi

ios - 从其他 ViewController 调用函数

转载 作者:行者123 更新时间:2023-11-30 12:47:24 25 4
gpt4 key购买 nike

我有两个 ViewController,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()
}
}

我希望能够调用func showAlert()SecondViewController当录音UIButton时在FirstViewController .

我已经花了很多个夜晚来寻找解决方案,但没有任何效果。有人知道如何实现这个目标吗?

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

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

最佳答案

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

SecondViewController 类的 viewDidLoad 方法中将自身注册为观察者以接收通知广播:-

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

关于ios - 从其他 ViewController 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41461690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com