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 can download 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 the free icon from Pixeden)

Importing the SWRevealViewController Library

As mentioned, we’ll use the free SWRevealViewController library to implement the slide-out menu. So, first download the library from GitHub and 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];
    
    return cell;
}

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 = [NSString stringWithFormat:@"%@_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.

iphone Dev 开发实例10:How To Add a Slide-out Sidebar Menu in Your Apps的更多相关文章

  1. iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

    In this tutorial, we will build a simple app to display a collection of recipe photos in grid layout ...

  2. iphone Dev 开发实例8: Parsing an RSS Feed Using NSXMLParser

    From : http://useyourloaf.com/blog/2010/10/16/parsing-an-rss-feed-using-nsxmlparser.html Structure o ...

  3. iphone dev 入门实例7:How to Add Splash Screen in Your iOS App

    http://www.appcoda.com/how-to-add-splash-screen-in-your-ios-app/ What’s Splash Screen? For those who ...

  4. iphone dev 入门实例6:How To Use UIScrollView to Scroll and Zoom and Page

    http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content Getting Starte ...

  5. iphone dev 入门实例5:Get the User Location & Address in iPhone App

    Create the Project and Design the Interface First, create a new Xcode project using the Single View ...

  6. iphone dev 入门实例4:CoreData入门

    The iPhone Core Data Example Application The application developed in this chapter will take the for ...

  7. iphone dev 入门实例1:Use Storyboards to Build Table View

    http://www.appcoda.com/use-storyboards-to-build-navigation-controller-and-table-view/ Creating Navig ...

  8. iphone dev 入门实例3:Delete a Row from UITableView

    How To Delete a Row from UITableView I hope you have a better understanding about Model-View-Control ...

  9. iphone dev 入门实例2:Pass Data Between View Controllers using segue

    Assigning View Controller Class In the first tutorial, we simply create a view controller that serve ...

随机推荐

  1. (转)Hadoop数据类型

    来源: http://www.cnblogs.com/anny-1980/articles/2608097.html BooleanWritable:标准布尔型数值 ByteWritable:单字节数 ...

  2. 20145220 实验五 Java网络编程

    20145220 实验五 Java网络编程 实验内容 1.用书上的TCP代码,实现服务器与客户端. 2.客户端与服务器连接 3.客户端中输入明文,利用DES算法加密,DES的秘钥用RSA公钥密码中服务 ...

  3. linux环境进程的停止

    使用 #ps auxf|grep 你想要获取的进程,如下,我想要获得的是nginx的进程号 图中黄色的便是进程号, 在此我们想kill掉主进程就要把后面有master字样的进程号kill掉 命令如下 ...

  4. 【转】iOS 删除已经配置的类库和移除CocoaPods

    原文网址:http://www.jianshu.com/p/552f21a989ba 引言 我们使用CocoaPods非常高效地将一些第三方类库导入到我们的项目中,但是不由得产生一个疑问:如果发现某个 ...

  5. Xcode 7 ImageNamed 方法加载jpg图片失败

    更新XCode7后 原来的Image.xcassets文件夹变成了Assets.xcassets 把01.jpg,02.jpg,03.png拖入这个文件夹中 UIImage* test1=[UIIma ...

  6. SVG中的'defs' and 'use'-可复用的图元定义

    在下一个示例中,我使用了defs中的元素之前,定义了如何去展现图元. <?xml version="1.0" standalone="no"?> & ...

  7. python pydoc

    pydoc是Python自带的模块,主要用于从python模块中自动生成文档,这些文档可以基于文本呈现的.也可以生成WEB 页面的,还可以在服务器上以浏览器的方式呈现! windows powersh ...

  8. 详尽介绍FireFox about:config

    一.什么是about:config about: config: 是Firefox的设置页面,Firefox提供了不少高级设置选项在这里以便让你可以更加详细地控制Firefox的运行方式.官方不推荐 ...

  9. Dom之标签增删操作

    dom操作:THML新增子标签 a标签(appendChild) <!DOCTYPE html><html lang="en"><head> & ...

  10. System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

    系统debug时出现错误,System.AccessViolationException: 尝试读取或写入受保护的内存.这通常指示其他内存已损坏. Attempted to read or write ...