Reputation: 2874
Using XCode 6.1 I am trying to roll my own View Controller containment with a custom menu... I am using the following function within my Main View Controller to present child view controllers:
var currentController: UIViewController?
// Function within main view controller class
func presentController(controller: UIViewController) {
if currentController != controller {
if currentController != nil {
currentController!.willMoveToParentViewController(nil)
currentController!.view.removeFromSuperview()
currentController!.removeFromParentViewController()
}
controller.willMoveToParentViewController(self)
self.addChildViewController(controller)
self.view.addSubview(controller.view)
controller.didMoveToParentViewController(self)
currentController = controller
}
}
When the app is initially run I use self.presentController(firstViewController)
inside viewDidAppear
, which works.
However, in my custom menu (using REMenu) outside of the Main View Controller, I'm trying to display the selected view controller like so: MainViewController().presentController(secondViewController)
. When this runs the currentController gets removed (revealing the Main View Controller's view which is just a black background) but the new controller doesn't get loaded in.
Can anyone guide me in the right direction?
Upvotes: 3
Views: 3623
Reputation: 438212
Assuming that MainViewController
is the name of your main view controller's class, the following line probably does not do what you intend:
MainViewController().presentController(secondViewController)
The MainViewController()
will instantiate a new copy of the main view controller. I assume you meant to get a reference to the existing controller, not instantiate a new one.
Unrelated to your problem at hand, but you should not call willMoveToParentViewController
before calling addChildViewController
(because it does that for you). You only need to call didMoveToParentViewController
when you're done configuring the new controller's view. Thus:
func presentController(controller: UIViewController) {
if currentController != controller {
if currentController != nil {
currentController!.willMoveToParentViewController(nil)
currentController!.view.removeFromSuperview()
currentController!.removeFromParentViewController()
}
// controller.willMoveToParentViewController(self)
self.addChildViewController(controller)
self.view.addSubview(controller.view)
controller.didMoveToParentViewController(self)
currentController = controller
}
}
Upvotes: 6