I am programmatically setting up ViewControllers (no storyboard).
I want to pass data to the next VC, and while I know how to do that with a segue and a storyboard, I can't figure out how to do it purely programmatically.
I get the error "Instance Member Cannot Be Used on 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?
CarbonCalculatorResultsViewController.userInformation = userInformation
// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)
Do I need to instantiate the next VC before I can pass data? That's what this answer seems to talk about yet I don't have a Storyboard. Thanks!
Step 1: Setup your destination class
In CarbonCalculatorResultsViewController
class, declare a var
to receive data like so:
class CarbonCalculatorResultsViewController: UIViewController {
var foo: String? {
didSet {
// What you'd like to do with the data received
print(foo ?? "")
}
}
ovevride func viewDidLoad() {
//
}
}
Step 2: Prepare data in your source class
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)
Then, every time the CarbonCalculatorResultsViewController
comes alive, the didSet{}
of foo
would be called.