如何解决从另一个类加载函数在Swift IOS中崩溃
在导航控制器弹出回到ViewController1之前,我想从ViewController 2加载功能checkStatus()(这是ViewController1的一部分)。 不幸的是,当调用该函数时,该应用程序在加载后立即崩溃,我真的很沮丧,因为我不知道自己做错了什么。
ViewControllers嵌入在导航控制器中。
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)
}
我很感谢任何帮助。
解决方法
您可以使用委托模式在您的情况下调用函数。
ViewController代码:
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)
}
}
,
我已经将viewController推送到导航堆栈,然后弹出到根Viewcontroller。
第一个ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func firstAction(_ sender: Any) {
let vc = UIStoryboard.init(name: "Main",bundle: nil).instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.navigationController?.pushViewController(vc,animated: true)
}
func callFunc(){
print(#function)
}
}
第二个ViewController
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func secondAction(_ sender: Any) {
ViewController().callFunc()
self.navigationController?.popToRootViewController(animated: true)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。