我编程设置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但我没有故事板。谢谢!
第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
会被调用。
当前样本代码(上文)设定一个值,以一个静态变量(由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
。
你应该通过变量的Object
,而不是在Class
替换:CarbonCalculatorResultsViewController.userInformation = userInformation
附:nextViewController.userInformation = userInformation
注意:
CarbonCalculatorResultsViewController
是Class
。
nextViewController
是Object
。
你完整的代码应该是这样的:
// 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)