I'm trying to load another UIViewController
so that I can get the data of the IBOutlets
inside of it. I'm using Swift and Sprite-Kit. The UIViewController
I am talking about is called GameViewController
. It is the first thing that loads up in my game. Then it goes to my GameScene
. This is where I am trying to instantiate my GameViewController
. I want to do this because I am using a library called iCarousel
and I want to animate it moving up from my GameScene
. However, iCarousel can only be used on a UIViewController
. So I want to call a function in GameViewController
that will be called in GameScene
. In this function, there is an NSLayoutConstraint
that is used to move the carousel. Whenever I call this function, it says that its nil. Here is some of my code:
Inside my GameScene
:
let storyboard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let firstViewController: GameViewController = storyboard.instantiateViewControllerWithIdentifier("Load-up") as! GameViewController
firstViewController.start()
Inside my GameViewController
:
func start() {
// Constraint
top.constant = 100
UIView.animateWithDuration(2){
self.view.layoutIfNeeded()
}
}
If you need more information, feel free to ask me. Thanks in advance!
That is because your view controller hasn't loaded its view hierarchy yet. viewController
loads its view hierarchy only when something sends it a view
message. The system will do this by its own when to put the view
hierarchy on the screen. And it happens after calls like prepareForSegue:sender:
and viewWillAppear:
, loadView()
, self.view
.
So here your outlets
are still nil
since it is not loaded yet.
Just try to force your VC to call self.view
and then access the properties/outlets.
Edit: Added sample code.
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewControllerWithIdentifier("Load-up") as! GameViewController
debugPrint("Printing for the sake of initializing view of VC: \(firstViewController.view)")
firstViewController.start()