gpt4 book ai didi

ios - 从另一个类加载函数在 Swift IOS 中崩溃

转载 作者:行者123 更新时间:2023-12-02 07:28:18 27 4
gpt4 key购买 nike

我想在导航 Controller 弹回 ViewController1 之前从我的 ViewController 2 加载函数 checkStatus()(它是我的 ViewController1 的一部分)。
不幸的是,在调用该函数时,应用程序一加载就崩溃了,我真的很沮丧,因为我不知道自己做错了什么。
ViewController 嵌入在导航 Controller 中。
ViewController1 中的代码:

func checkStatus(){
/* setting Label texts (Outlets) to a specific value but it is
irrelevant as the compiler does not even get to
this point. The program crashes as soon as the function is called (tried it with prints).*/
ViewController2 中的代码:
@IBAction func didTapBack(_ sender: UIButton){
// first the function is animating something inside the VC2
ViewController1().checkStatus() // function gets called here
self.navigationController?.popToRootViewController(animated: false)
}
我很感激任何帮助。

最佳答案

您可以使用委托(delegate)模式在您的情况下调用函数。
View Controller 代码:

import UIKit

class ViewController: UIViewController, SecondViewControllerDelegate {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

}

@IBAction func gotoSecondVC(_ sender: UIButton) {

let secondVC = self.storyboard?.instantiateViewController(identifier: "SecondViewController") as! SecondViewController
secondVC.delegate = self
self.navigationController?.pushViewController(secondVC, animated: true)

}

func checkStatus() {
print("\(#function) called...")
}

}
SecondViewController 代码:
import UIKit

protocol SecondViewControllerDelegate: class {
func checkStatus()
}

class SecondViewController: UIViewController {

weak var delegate: SecondViewControllerDelegate?

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

@IBAction func backButtonTapped(_ sender: UIButton) {
delegate?.checkStatus()
self.navigationController?.popViewController(animated: true)
}

}

关于ios - 从另一个类加载函数在 Swift IOS 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63965981/

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