Add a sidebar panel to your iOS app

Original author: Simon Ng
  • Transfer
  • Tutorial
As a translator, I apologize in advance for possible errors in the translation. I would be grateful for error messages to correct them as soon as possible.

How can I add a sidebar to my iOS app? This is one of the most frequently asked questions that we receive from our readers. Today we will show how to create a side menu like the one you can see, for example, in a Facebook application.

For those who are not familiar with the concept of a side menu in mobile applications, Ken Yarmost gave a good explanation of this interface element and defined it as:
The side menu is a panel that “rolls out” from below, to the left or to the right of the main content area of ​​the application, containing a vertical scroll independent of the main content of the application and serves as the main navigation tool in the application.

Since Facebook introduced the side menu in its mobile application, this interface element has quickly become the standard for implementing application navigation. In one form or another, you can see the side menu in such popular applications as Path, Mailbox, Gmail, Evernote, etc.



Using the side menu allows you to implement navigation without taking up precious space from the main content on the screen of a mobile device, because in an inactive state such a menu is hidden behind a layer of the main content of the application. The menu can be called up by pressing the menu button on the navigation bar. After the menu has become active, the user can close it using the same menu button on the navigation bar or simply swipe left along the active content area of ​​the application.

With a huge number of solutions on GitHub , we will not begin to build our side menu from scratch. Instead, we will use the wonderful SWRevealViewController library . Developed by John Lluch, this is a free library that provides a quick and easy way to implement sidebar menus.

Well, let's try to develop an example application together.

Demo Application Overview


As usual, we will develop a demo application to show you how to use the SWRevealViewController library. The application is very simple and its main purpose is to guide you through the process of implementing the side menu in your iOS application. Our navigation menu will work as follows:

  • The menu is called up by pressing the “menu” button in the upper left corner of the navigation panel;
  • Also, the menu can be called up by swiping right to the active content area;
  • The user can close the active side menu by pressing the "menu" button in the upper left corner of the navigation panel;
  • Also, the menu can be closed by swiping left on the active content area.



Create a project in Xcode


With the introduction of the main idea of ​​the application, we move on. You can create an Xcode project from scratch and design a user interface similar to the one below:



However, to save time, you can download the Xcode project template , which already includes:

  • Ready storyboard with all the controllers we need;
  • Ready-made view controller classes, including MapViewController and PhotoViewController;
  • MapViewController implements map display;
  • PhotoViewController implements the display of photographs and images;
  • All icons and images necessary for the application (thanks to the free icons from Pixeden )


Import SWRevealViewController library


As already mentioned, we will use the free SWRevealViewController library to implement the side menu. First you need to download the library from GitHub and extract the files from the downloaded archive.

After unpacking the archive, you need to find the files “SWRevealViewController.h” and “SWRevealViewController.m”. Right-click on the SidebarDemo folder in the project navigator window and create a new group of files by selecting “New Group” in the pop-up context menu. Name the group "SWRevealViewController". Import both files into an Xcode project by placing them in the "SWRevealViewController" group.



Linking view content view controllers and slide-out menu backends


One of the great features of the SWRevealViewController library is its native Storyboard support. When implementing the side menu using the SWRevealViewController, the developer must associate the SWRevealViewController with the view controllers of the main content of the application (top layer) and the side menu layer (background) using segues. In our layout, the top layer is the Navigation Controller associated with the View Controller to display news, and the bottom layer is the View Controller containing the navigation menu. Typically, a menu is implemented using the UITableViewController.



In our project template for Xcode, view controllers for the top and bottom layers are already created. All you have to do is define segues between the SWRevealViewController and the content view controllers and the menu background.

To get started, select the starting View Controller and change its class to “SWRevealViewController”.



Then, by pressing and holding the control key on the keyboard, click on the view controller SWRevealViewController and drag the mouse to the Menu View Controller. After you release the key, you will see a context menu for segue selection. In this case, we need to select “reveal view controller set segue”. This will define the user segue "SWRevealViewControllerSetSegue". This segue tells SWRevealViewController that this View Controller is the source view controller.

Note: If you are using an older version of SWRevealViewController, please note that using SWRevealViewControllerSegue is deprecated and you must use SWRevealViewControllerSetSegue.


Repeat the same procedure to connect the main view controller (the main view containing the news) to the SWRevialViewController.



Select a Segway between SWRevealViewController and Navigation Controller. Assign the identifier “sw_front” for this transition in the attributes inspector. This is a predefined identifier indicating a transition to the front view controller (news).

For the segway between the SWRevealViewController and the side menu view controller, set the identifier to "sw_rear". This identifier tells SWRevealViewController that this controller is a “backing” (ie, a side menu).



If you compile and run the application, you will see the application displaying the news. And it's all. You will not see the side menu by clicking on the menu button on the left side of the navigation panel. And all because we have not yet implemented the action method for pressing this button.

Open MainViewController.m, which is the News Frontpage controller class. Add the following import statement:

#import "SWRevealViewController.h"


Then add the following code to the viewDidLoad method :

SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController )
    {
        [self.sidebarButton setTarget: self.revealViewController];
        [self.sidebarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }


SWRevealViewController provides the revealToggle: method to control the display of the side menu. As you know, Cocoa uses the target-action mechanism for communication between the controller and other objects. As the target for the menu button, we set the View Controller of the navigation bar, and as an action, the revealToggle: method . Now, when the user touches the side menu display button, the revealToggle: method will be called , which will display the side menu. Finally, we added gesture recognition. Now the user can call up the menu not only by pressing a button, but also using a swipe in the display area of ​​the main content of the application.

Try compiling and running the application on an iPhone simulator. Click on the "menu" button and the application should show you a sidebar menu. Click on the button again to close it. You can also open the menu using swipe to the right.



Before continuing, add the same code snippets to the viewDidLoad method : in the PhotoViewController.m and MapViewController.m files. The application should display the sidebar of the menu when the user presses the menu button in these two view controllers.

Adding items to the navigation menu


With just a few lines of code, you have implemented the outgoing side menu. Great, isn't it?

However, the menu now does not contain any items. We will add several menu items and show you the implementation of the transition from one item to another. For simplicity, we will design our menu directly on the storyboard.

The first cell of the table contains the heading "APPCODA". You can replace this heading with any other, at your discretion. The only thing you must observe is the identifiers of the cells, which we will use in our code later.

Ok, let's add some menu items. First, select the cell prototype and in the attribute inspector increase the number of prototypes to 8. As a result, you should get a screen similar to the screen below:



Change the inscription of the second cell from “APPCODA” to “News”. If you want, you can change the color of the text to dark gray and change the font to “Avenir Next” in the Attributes inspector. Then, move to the image view cell from the object library. Set the size to 38x38 and set the image to “news.png” for this object.

Next, give the cell the identifier “news” in the attribute inspector. As a result, you should get a cell similar to the one you see in the image below:



Repeat the same procedures to get the following menu items:

  • Comments (image comments.png and comments cell id)
  • Map (image map.png and map cell id)
  • Calendar (image calendar.png and cell id calendar)
  • Wishlist (wishlist.png image and wishlist cell id)
  • Bookmark (image bookmark.png and cell ID bookmark)
  • Tag (image tag.png and tag cell id)

If you did everything right, then your navigation bar will look something like this:



After finishing work on the user interface, let's implement the code to display the cells of the navigation table. Open the “SidebarViewController.m” file and add the following import statement to it:

#import "SWRevealViewController.h"


Next, declare the menuItems variable to hold the menu item identifiers.

@implementation SidebarViewController {
    NSArray *menuItems;
}


The code above is very simple. We initialized the array with the value elements of the identifiers of the menu item cells. Then adjust the numberOfSectionsInTableView method : so that it returns 1 and the numberOfRowsInSection method : - it should return the correct number of rows in the table:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return menuItems.count;
}


Finally, change the cellForRowAtIndexPath: method as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    return cell;
}


This code simply gets the table cell identifier from the menuItems array to display it later. Now compile and run the application again. Click on the menu display button and this time you will see the navigation menu bar containing the items.



Implementing a selection of menu items


You have already developed the app with a visually appealing side menu. But we missed something. We did not define any transitions for menu items. When choosing any of the menu items, we do not go to any of the corresponding representations.

In order not to complicate the demo, we will connect only three view controllers to the menu items. I think it will very well demonstrate to you the principle of work. Here is what we are going to do:

  • Connect the cell with the item “News” to the main view controller using the “reveal view controller push controller” segway
  • Connect the cell with the “Map” item to the map view controller using the “reveal view controller push controller” segway
  • All other cells of the menu items will be connected to the controller of the photo view using the same type of Segway. However, for each menu item its own photo will be displayed.


So let's get back to the storyboard. To get started, select the cell with the identifier "map" (map). Press and hold the control key on the keyboard and click on the “map” cell. Drag the mouse cursor to the map view controller and select the “reveal view controller push controller” in the Selection Segue section.



Repeat this procedure for the News cell, but connect it to the main view controller.

For each of the menu items comments, calendar, wishlist, bookmark and tag, connect them one by one to the navigation controller of the photo view controller and assign the identifier “showPhoto” to each of the created transitions. We will use this identifier to distinguish these segways from the two previous ones.



After completing the configuration of the segways in the storyboard, open “SidebarViewController.m”. To get started, add an import statement:

#import "PhotoViewController.h"


Then add the prepareForSegue: method to control the transition:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Set the title of navigation bar by using the menu items
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    UINavigationController *destViewController = (UINavigationController*)segue.destinationViewController;
    destViewController.title = [[menuItems objectAtIndex:indexPath.row] capitalizedString];
    // Set the photo if it navigates to the PhotoView
    if ([segue.identifier isEqualToString:@"showPhoto"]) {
        UINavigationController *navController = segue.destinationViewController;
        PhotoViewController *photoController = [navController childViewControllers].firstObject;
        NSString *photoFilename = [NSString stringWithFormat:@"%@_photo", [menuItems objectAtIndex:indexPath.row;
        photoController.photoFilename = photoFilename;
    }
}


In the code above, we first get the identifier of the current cell and set it as the title for the navigation bar. For Segways with the identifier “showPhoto”, the photo view controller will display only one photo. In this code, we specify the image file name that we will display. For example, when the user selects the “Comments” item, we will display “comments_photo.jpg”.

Final compilation and testing of the application


Now compile and test the application again. Open the side menu and select "Map". You will be directed to the map display section. Try to test the transition to other menu items and see what happened.



To summarize


In this tutorial, we showed you how to use SWRevealViewController to implement a sidebar panel similar to a Facebook application. On GitHub, you can find many other solutions for implementing a similar menu, such as GHSidebarNav and ViewDeck . You can freely explore other libraries and choose the ones that are best suited for your applications. If you want to learn how to build your side menu from scratch, Ray Wenderlich offers a wonderful lesson .

Also popular now: