iphone Dev 开发实例10:How To Add a Slide-out Sidebar Menu in Your Apps


Creating the Xcode Project

With a basic idea about what we’ll build, let’s move on. You can create the Xcode project from scratch and design the user interface similar to below:

Storyboard of the Demo App

However, to save your time from setting up the project, you candownload the Xcode project templateto start with.

The project already comes with:

  • A pre-built storyboard with all the view controllers needed
  • A pre-built view controller classes including MapViewController and PhotoViewController
  • All icons and images needed for the app (credit: thanks for thefree icon from Pixeden)

Importing the SWRevealViewController Library

As mentioned, we’ll use the free SWRevealViewController library to implement the slide-out menu. So, firstdownload the library from GitHuband extract the zipped file.

After you extract the file, you should find “SWRevealViewController.h” and “SWRevealViewController.m”. Import both files into the Xcode project and put them under “Library”.

Import SWRevealViewController into Library

Associate the Front View and Rear View Controller

One of the beauties of the SWRevealViewController library is it provides the built-in support of Storyboard. Of course, if you prefer, you can also use Interface Builder to create the sidebar menu. But from what we know, most of you opt for Storyboard to design the user interface.

When implementing sidebar menu using SWRevealViewController, developers have to associate the SWRevealViewController with a front and a rear view controller using segues. The front view controller is the main controller for displaying content. In our storyboard, it’s the navigation controller which associates with another view controller for presenting news content. Apparently, the rear view controller is the controller for showing the navigation menu. Usually the menu is implemented by using UITableViewController.

Front and Rear View of SWRevealViewController

If you’re using our Xcode template, we’ve pre-built the front and rear view controllers for you. What you have to do is to define segues between the SWRevealViewController and front/rear view controller.

First, select the empty UIViewController and change its class to “SWRevealViewController”.

Changing the class to SWRevealViewController

Next, press and hold the control key. Click on the SWRevealViewController and drag it to the Sidebar view controller. After releasing the button, you’ll see a context menu for segue selection. In this case, select “reveal view controller”. This defines a custom segue by using “SWRevealViewControllerSegue”.

Repeat the same procedures to connect SWRevealViewController with the navigation controller.

Defining Segues for SWRevealViewController

Select the segue between SWRevealViewController and the navigation controller. In the attributes inspector, set the segue identifier to “sw_front”. This is the default identifier to indicate a transition of front view controller.

For the segue between SWRevealViewController and the sidebar view controller, set the segue identifier to “sw_rear”. This identifier tells SWRevealViewController that the controller represents the rear view (i.e. the sidebar menu).

Setting the segue identifier for front and rear view controllers

If you compile and run the app, you’ll see an app displaying the “News Frontpage”. But that’s it. You won’t see the sidebar menu when tapping the list button. We haven’t implemented the action method yet.

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

1
#import "SWRevealViewController.h"

Next, add the following code in the viewDidLoad method:

1
2
3
4
5
6
7
8
9
// Change button color
_sidebarButton.tintColor=[UIColor colorWithWhite:0.96f alpha:0.2f];

// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target=self.revealViewController;
_sidebarButton.action=@selector(revealToggle:);

// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];

We first change the list button color and then assign the list button with an action. The SWRevealViewController provides a “revealToggle:” method to handle the expansion and contraction of the sidebar menu. Lastly, we also add a gesture recognizer. Not only you can use the list button to bring out the sidebar menu, user can swipe the content area to activate the sidebar.

Try to compile and run the app. Tap the list button and the sidebar menu will be appeared. Tap the button again to close it. You can also swipe right on the content area to open the menu.

Before moving on, add the same code snippet to both PhotoViewController.m and MapViewController.m.

Adding the Menu Items in Navigation Menu

With just a few lines of code, you already implement the slide-out navigation menu. Cool, right?

However, the menu is now empty. We’ll now add a few items and show you the transition from one item to another. The sidebar view controller is just a simple table view controller. For sake of simplicity, we’ll design the sidebar menu right in the storyboard.

The first table cell is defined with the title of our website. If you don’t like it, just change it to whatever you prefer. Just make sure you keep the cell identifier as “title”, which we’ll refer it in our code.

Okay, let’s add a few more menu items. To begin, select the prototype cell and change the number of prototype cells to “8″ in the attributes inspector. You should end up with a screenshot similar to below:

Changing the number of prototype cells

Change the “APPCODA” label of the second cell to “News”. Optionally, you can change the color of label to light gray and set the font to “Helvetica Light” in the attributes inspector. Next, drag a image view object from the object library to the cell. Set the size of image view to 38×38 and change the image to “news.png”.

Next, select the cell and set the cell identifer as “news” in the attributes inspector. You should end up with a cell similar to the below screenshot:

News cell item with news identifier

Repeat the above procedures to add the following menu items:

  • Comments (set the images as comments.png and cell identifier as comments)
  • Map (set the images as map.png and cell identifier as map)
  • Calendar (set the images as calendar.png and cell identifier as calendar)
  • Wishlist (set the images as wishlist.png and cell identifier as wishlist)
  • Bookmark (set the images as bookmark.png and cell identifier as bookmark)
  • Tag (set the images as tag.png and cell identifier as tag)

If you’ve done everything correct, your menu should look like this:

After completing the user interface, let’s go back to the code. Select the “SidebarViewController.m” and import the following header files:

1
2
#import "SWRevealViewController.h"
#import "PhotoViewController.h"

Next, declare the following property to store the cell identifier of the menu items:

1
@property(nonatomic, strong)NSArray*menuItems;

In the viewDidLoad method, add the following code:

1
2
3
4
5
self.view.backgroundColor=[UIColor colorWithWhite:0.2f alpha:1.0f];
self.tableView.backgroundColor=[UIColor colorWithWhite:0.2f alpha:1.0f];
self.tableView.separatorColor=[UIColor colorWithWhite:0.15f alpha:0.2f];

_menuItems=@[@"title",@"news",@"comments",@"map",@"calendar",@"wishlist",@"bookmark",@"tag"];

The above code is very straightforward. We first set the background color of the view and table view and initialize the menu item array with the values of cell identifier.

Then change the number of rows from 0 to [self.menuItems count]. Your code should look like this:

1
2
3
4
5
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return[self.menuItems count];
}

Lastly, change the “cellForRowAtIndexPath” method to the following. The code simply gets the cell identifier of the specified table cell from the menuItems array for display.

1
2
3
4
5
6
7
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
NSString*CellIdentifier=[self.menuItems objectAtIndex:indexPath.row];
UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

returncell;
}

Now compile and run the app again. Tap the list button and you’ll find a slide-out navigation menu with a much better design.

Implementing Menu Item Selection

You’ve already built a visually appealing sidebar menu. However, there is still one thing left. As of now, we haven’t defined any segues for the menu item. When you select any of the menu items, it won’t transit to the corresponding view.

To make the demo app simple, we’ll only connect the menu item with three view controllers. We think this should give a pretty good demonstration to show you how it works. Here are what we’re going to do:

  • Connect the “News” cell item with the main view controller using a reveal view controller segue
  • Connect the “Map” cell with the map view controller using a reveal view controller segue
  • For the rest of the menu items, they will be associated with the photo view controller using the same type of segue. But we’ll display different photos for different menu items.

Okay, go back to storyboard. First, select the map cell. Press and hold the control key and click on the map cell. Drag to the map view controller. Select the “reveal view controller” segue when prompted.

Connecting the map item with map view controller

Repeat the above procedure for the “News” cell item, but connect it with the main view controller.

For the rest of menu items including comments, calendar, wishlist, bookmark and tag, connect them one by one with the photo view controller and set the segue identifier as “showPhoto”. We’ll use this identifier to differentiate the segue from the previous two we created.

Defining showPhoto as the segue identifier

Open the “SidebarViewController.m”, add the “prepareForSegue” method to manage the transition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
-(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"]){
PhotoViewController*photoController=(PhotoViewController*)segue.destinationViewController;
NSString*photoFilename=[NSStringstringWithFormat:@"%@_photo.jpg",[_menuItems objectAtIndex:indexPath.row]];
photoController.photoFilename=photoFilename;
}

if([segue isKindOfClass:[SWRevealViewControllerSegue class]]){
SWRevealViewControllerSegue*swSegue=(SWRevealViewControllerSegue*)segue;

swSegue.performBlock=^(SWRevealViewControllerSegue*rvc_segue, UIViewController*svc, UIViewController*dvc){

UINavigationController*navController=(UINavigationController*)self.revealViewController.frontViewController;
[navController setViewControllers:@[dvc]animated:NO];
[self.revealViewController setFrontViewPosition:FrontViewPositionLeft animated:YES];
};

}

}

Let us go through the above code line by line:

  • Line 4 to 6 are used to set the title of the navigation bar. We simply use the cell identifier as title.
  • Line 9 to 13 are only for those segues with “showPhoto” identifier. The photo view controller will only display a single photo. Here we set the file name of the photo to be displayed. Say, when user taps the “Comments” item, we’ll show the “comments_photo.jpg”.
  • Line 15 to 25 are the code to manage the view transition and tell SWRevealViewController the new front view controller for display. We reuse the navigation controller and replace the view controller with destination view controller.

Compile and Test the Final App

Now compile and test the app again. Open the sidebar menu and tap the map item. You’ll be brought to the map view. Try to test other menu items and see what you get.

优质内容筛选与推荐>>
1、5款优秀免费在线数据备份/存储工具
2、IPC通信:Posix共享内存2
3、(转)进一步理解javascript对象、数组和哈希表
4、【OpenGL】Shader实例分析(五)- 边缘检测
5、[Java笔记]面向对象-单例模式


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn