简体   繁体   English

初始化变量有麻烦

[英]Having trouble initializing variable

I'm trying to initialize a variable in a view controller before that view controller takes over the view, and it seems no matter how I try to initialize it, it doesn't work and the software runs as if the value is the default value. 我正在尝试在该视图控制器接管该视图之前在该视图控制器中初始化一个变量,并且似乎无论我如何尝试对其进行初始化,它都无法正常工作,并且软件会像默认值一样运行。 Part of the problem seems to be the view that contains the variable in question is nil when I try to set the variable's value. 问题的一部分似乎是当我尝试设置变量值时,包含相关变量的视图为nil。 I don't know why this is. 我不知道为什么会这样。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢! Here is my code: 这是我的代码:

override func setStartPosition()
{
    if sessionNameIndex != nil
    {
        if let curSession = ShareData.sharedInstance.sessionDataObjectContainer[sessionNames[sessionNameIndex]]
        {
            initialValue = YesNo(rawValue: (curSession.currentValue))

            if mySessionDisplay == nil
            {
                mySessionDisplay = SessionDisplayView(frame: self.view.frame)
                if mySessionDisplay == nil
                {
                    var shouldneverbehere = 0  //Always goes here!
                }
                else
                {
                    mySessionDisplay.onView(index: 2, sessionName: sessionNames[sessionNameIndex])
                    mySessionDisplay.curScene.setStartPosition(newValue: val!)
                }

            }



        }
    }
}

This function gets called in the following code: 在以下代码中调用此函数:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

    if let destination = segue.destination as? SessionDisplayViewControllerTwo
    {
        if let myNames = sender as? [String]
        {
            destination.sessionNames = myNames
            destination.sessionNameIndex = 1
            destination.setStartPosition()
        }
    }
}

Let me know if you need more information. 如果您需要更多信息,请与我们联系。 Once again, thanks for your consideration of this matter. 再次感谢您对此事的考虑。

A view controller's views have not yet been loaded in prepareForSegue . 视图控制器的视图尚未在prepareForSegue加载。 As @muescha suggests in his comment, you should set properties in prepareForSegue , and then wait for viewDidLoad or viewWillAppear before you try to install them in your views. 就像@muescha在他的评论中建议的那样,您应该在prepareForSegue设置属性,然后等待viewDidLoadviewWillAppear然后再尝试在视图中安装它们。 I'm not sure why your attempt to manually create your SessionDisplayView is failing, but you should not be trying to create views in prepareForSegue in any case, so the solution is "Don't do that." 我不确定为什么您手动创建SessionDisplayView尝试失败了,但是SessionDisplayView您都不应该尝试在prepareForSegue中创建视图,因此解决方案是“不要那样做”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM