使用共享实例设置 viewController 属性仍然为零 [英] Setting a viewController property by using a shared instance remains nil

查看:20
本文介绍了使用共享实例设置 viewController 属性仍然为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个视图控制器:
1/LoginViewController
2/BibliothequeViewController

我通过单击 LoginViewController 中的按钮来呈现 BibliothequeViewController,同时尝试与 BibliothequeViewController 沟通它是 >LoginViewController 呈现它.

I am presenting BibliothequeViewController by clicking on a button inside LoginViewController and in the same time trying to communicate to BibliothequeViewController that it was LoginViewController that presented it.

所以在 LoginViewController 里面,我有这个:

So inside LoginViewController, I have this:

  @IBAction func onLibrariesButtonClicked(_ sender: Any) {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc: BibliothequesViewController = storyboard.instantiateViewController(withIdentifier: "BibliothequesViewController") as! BibliothequesViewController
        BibliothequesViewController.sharedInstance.presentedBy=self
        print("INSIDE LoginViewController.onLibrariesButtonClicked, BibliothequesViewController.sharedInstance.presentedBy",BibliothequesViewController.sharedInstance.presentedBy!)
        // Logs LoginViewController
        self.present(vc, animated: true, completion: nil)
    }

BibliothequesViewController 里面,我有这个:

Inside BibliothequesViewController, I have this:

class BibliothequesViewController: UIViewController {
    // presentedBy represents which view has presented the BibliothequesViewController
    // So that when a library is selected, I go back to the ViewController that presented BibliothequesViewController
    var presentedBy: UIViewController?
   override func viewDidLoad() {
        super.viewDidLoad()
       print("INSIDE viewDidLoad, presentedBy: ",presentedBy) 
       // Logs nil
    }
  }

如您所见,在 LoginViewController 代码中,BibliothequesViewController.sharedInstance.presentedBy 已设置为 LoginViewController.

So as you see, in the LoginViewController code, BibliothequesViewController.sharedInstance.presentedBy has been set to LoginViewController.

但是在BibliothequeViewController里面,它是nil,而它应该是LoginViewController.

But inside BibliothequeViewController, it is nil, when it should be LoginViewController.

推荐答案

我试过了:

 print("INSIDE BibliothequesViewController, BibliothequesViewController.sharedInstance.presentedBy",BibliothequesViewController.sharedInstance.presentedBy!)

我得到了 LoginViewController 的记录.所以我得到了我需要的东西.

And I got LoginViewController logged. So I got what I needed.

但我希望上面的代码也能工作.

But I expected the code above to work too.

这篇关于使用共享实例设置 viewController 属性仍然为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆