I am trying to make a sidebar menu but i have a little problem.
I explain :
In my viewController Class (the initial view controller), in the header file, i import my class SideMenuViewController and i wrote :
-(IBAction)openSideMenu:(id)sender;
@property(nonatomic, retain) SideMenuViewController *sideMenu;
The openSideMenu action is associated to the menu button.
I implemented this method like this :
- (IBAction)openSideMenu:(id)sender {
CGRect destination = self.view.frame;
if(destination.origin.x > 0){
destination.origin.x = 0;
}else{
destination.origin.x += SideMenuX;
}
[UIView animateWithDuration:0.4 animations:^{
self.view.frame = destination;
}completion:^(BOOL finished) {
if(finished){
}
}];
}
SideMenuX is a macro : #define SideMenuX 154.4
My viewDidLoad method looks like this :
- (void)viewDidLoad
{
[super viewDidLoad];
_sideMenu = [[SideMenuViewController alloc] init];
[self.view sendSubviewToBack:_sideMenu.view];
// Do any additional setup after loading the view, typically from a nib.
}
The problem is that when i click on the menu button, i get a black screen and not my side menu view.
Thank you in advance !
Two problems:
self.view.superview
), which in your case most likely will be the UIWindow: [self.view.superview insertSubview:_sideMenu.view belowSubview:self.view];If you are using a navigation controller, use
self.navigationController.view
instead self.view
. Here is a working example. I created the left view controller inside the storyboard like this:
SideMenuViewController
SideMenuViewController
Instantiate the controller inside viewDidLoad with
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
self.sideMenu = (SideMenuViewController*)[storyboard instantiateViewControllerWithIdentifier:@"SideMenuViewController"];
then insert it as child of the superview.
(Answering the comment below)
This line is the problem:
[self.view.superview addSubview:_sideMenu.view];
In a NIB based project the superview is UIWindow, but in a Storyboard project, the self.view.superview of a UIViewController is nil. You can solve this, for example, adding a UINavigationViewController. Follow these steps:
Then change your code to
_sideMenu = [[SideMenuViewController alloc] initWithNibName:@"SideMenuViewController" bundle:nil];
[self.navigationController.view.superview insertSubview:_sideMenu.view belowSubview:self.navigationController.view];
To hide the navigation bar of the UINavigationController, select it in the Storyboard and click Hidden in the Attributes Inspector (alt+cmd+4).