实例成员不能被推动的UIViewController当类型用于

问题描述 投票:0回答:3

我编程设置ViewControllers(无故事板)。

我想将数据传递到下一个VC,而我知道该怎么做了赛格瑞和故事板,我无法弄清楚如何做到这一点纯粹的编程。

我得到的错误“的实例成员中不能使用的类型。”

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller.  There is already a variable in that file: var userInformation: UserInformation?

CarbonCalculatorResultsViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

我需要实例化下一个VC之前,我可以传递数据?这就是this answer seems to talk about但我没有故事板。谢谢!

ios swift uinavigationcontroller swift4 programmatically-created
3个回答
1
投票

第1步:设置你的目标类

CarbonCalculatorResultsViewController类,声明var收到像这样的数据:

class CarbonCalculatorResultsViewController: UIViewController {
    var foo: String? {
        didSet {
            // What you'd like to do with the data received
            print(foo ?? "")
        }
    }

    ovevride func viewDidLoad() {
       //
    }
}

第2步:在您的源类准备数据

let nextViewController = CarbonCalculatorResultsViewController()
// You have access of the variable in CarbonCalculatorResultsViewController
nextViewController.foo = <data_you_want_to_pass>

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

然后,每次CarbonCalculatorResultsViewController来活着的时候,didSet{}foo会被调用。


1
投票

当前样本代码(上文)设定一个值,以一个静态变量(由CarbonCalculatorResultsViewController.Type拥有。

我相信你想要实现的是以下代替:

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller.  There is already a variable in that file: var userInformation: UserInformation?

nextViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

此示例代码设定值对类型userInformation实例变量nextViewController


1
投票

你应该通过变量的Object,而不是在Class

替换:CarbonCalculatorResultsViewController.userInformation = userInformation

附:nextViewController.userInformation = userInformation

注意:

CarbonCalculatorResultsViewControllerClass

nextViewControllerObject

你完整的代码应该是这样的:

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller.  There is already a variable in that file: var userInformation: UserInformation?

nextViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)
© www.soinside.com 2019 - 2024. All rights reserved.