Attempts to programmatically expose the View View controller
Using XCode 6.1 I am trying to roll my own View Controller wrapper with a custom menu ... I am using the following function in my Main View controller to present controllers to child views:
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 starts, I use self.presentController(firstViewController)
inside viewDidAppear
that works.
However, in my custom menu (using REMenu ) outside the main view controller, I'm trying to display the selected view controller like this: MainViewController().presentController(secondViewController)
. When this runs, the current control is removed (showing the Main View Controller, which is just a black background), but the new controller is not loaded.
Can anyone guide me in the right direction?
source to share
Assuming that MainViewController
is the name of your main view controller class, the following line probably doesn't do what you assume:
MainViewController().presentController(secondViewController)
MainViewController()
will create a new copy of the main view controller. I am assuming that you wanted to get a reference to an existing controller and not create a new one.
Not related to your problem, but you shouldn't call willMoveToParentViewController
before calling addChildViewController
(because it does it for you). You only need to call didMoveToParentViewController
when you're done setting up your new controller 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
}
}
source to share