Assigning View Controller Class

In the first tutorial, we simply create a view controller that serves as the detail view of recipe in the Storyboard editor. The view controller is assigned with the UIViewController class by default.

Default View Controller - UIViewController

Let’s revisit our problem. The label in the view should be changed with respect to the selected recipe. Obviously, there must be a variable in the UIViewController for storing the name of recipe.

The fact is the UIViewController class only provides the fundamental view management model. It corresponds to a blank view. There is no variable assigned for storing the recipe name. Thus, instead of using UIViewController directly, we extend from it and create our own class (known as the subclass of UIViewController).

In the Project Navigator, right-click the “RecipeBook” folder and select “New File…”.

Create New File in Xcode Project

Choose “Objective-C Class” under Cocoa Touch as the class template.

Select Objective C Class

Name the class as “RecipeDetailViewController” and it’s a subclass of “UIViewController”. Make sure you uncheck the option of “With XIB for user interface”. As we’re using Storyboards for designing the user interface, we do not need to create a separate interface builder file. Click “Next” and save the file in your project folder.

Create a RecipeDetailViewController class (Subclass of UIViewController)

Next, we have to assign the RecipeDetailViewController class to the view controller. Go back to the Storyboards editor and select the detail view controller. In the identity inspector, change the class to “RecipeDetailViewController”.

Change View Controller Class

Adding Variables to the Custom Class

We’ve just created our custom view controller class by extending from the UIViewController class. However, it doesn’t differ from the parent class until we add our own variables and methods. There are a couple of things we have to change:

  • Assign a variable (recipeName) for data passing – when user selects a recipe in the Recipe view, there must be a way to pass the name of recipe to the detail view.
  • Assign a variable (recipeLabel) for the text label – presently the label is static. It should be updated as the name of recipe changes.

Okay, let’s add these two variables (recipeLabel and recipeName). Select the “RecipeDetailViewController.h” and adds two properties for the interface:

1
2
3
4
5
6
@interface RecipeDetailViewController : UIViewController

@property (nonatomic, strong) IBOutlet UILabel *recipeLabel;
@property (nonatomic, strong) NSString *recipeName;

@end

Go to the “RecipeDetailViewController.m” and add the synthesis for the variables. Make sure you place the code under “@implementation RecipeDetailViewController”:

1
2
3
4
@implementation RecipeDetailViewController

@synthesize recipeLabel;
@synthesize recipeName;

If you’ve forgotten what the interface and implementation are, go back to this tutorial and revisit the concept.

Establish a Connection Between Variable and UI Element

Next, we have to link up the “recipeLabel” variable with the visual Label. In the Storyboards editor, press & hold the command key and then click the “Recipe Detail View Controller” icon, drag it to the Label object. Release both buttons and a pop-up shows variables for your selection. Choose the “recipeLabel” variable.

Establish the Connection between UI element and Variable

That’s it. Now you’ve linked up the variable with the Label UI element. Any change in the variable will be reflected visually. But there is still one thing left. We want to have the label to display the recipe name. So in viewDidLoad function, we add the following code that sets the label text the same as the recipe name.

1
2
3
4
5
6
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Set the Label text with the selected recipe
    recipeLabel.text = recipeName;
}

Try to compile and run your app. Oops! The detail view is completely blank after selecting any recipe. That’s the expected behavior. We haven’t written any code to pass along the recipe name. Yet, the “recipeName” variable is blank that contributes to the empty text label.

Receipe App with Empty Detail Controller

Passing Data Using Segue

This comes to the core part of tutorial about how to pass data between view controller using Segue. Segues manages the transition between view controllers. On top of this, segue objects are used to prepare for the transition from one view controller to another. When a segue is triggered, before the visual transition occurs, the storyboard runtime invokes prepareForSegue:sender: method of the current view controller (in our example, it’s the RecipeBookViewController). By implementing this method, we can pass any needed data to the view controller that is about to be displayed.

However, the best practice is to give each segue in your Storyboards an unique identifier. This identifier is a string that your application uses to distinguish one segue from another. As your app becomes more complex, it’s likely you’ll have more than one segue in the view controllers.

To assign the identifier, select the segue and set it in the identity inspector. Let’s name the segue as “showRecipeDetail”.

Storyboard Segue Identifier

Next, we’ll implement the prepareForSegue:sender: method in “Recipe Book View Controller”, which is the source view controller of the segue. Select the “RecipeBookViewController.m” and add the following code:

 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
    }
}

The prepareForSegue method will be called when the transition begins. The 1st line is used to verify the identifier of segue. In this case, the identifier is “showRecipeDetail”. The 2nd line of code invokes the tableView:indexPathForSelectedRow to retrieve the selected table row. Once we have the selected row, we’ll pass it to the RecipeDetailViewController. A Segue object contains the view controller whose contents should be displayed at the end of the segue. You can always use “segue.destinationViewController” to retrieve the destination controller. In this case, the destination controller is the RecipeDetailViewController. The rest of the code is to pass the recipe name to the destination controller.

You can’t run your app right now. After you copy & paste the above method into RecipeBookViewController.m, you should see a number of errors.

prepareForSegue Error

There are three errors as shown above. But we can summarize them into two:

  • The property “tableView” is not found in RecipeDetailViewController.
  • What’s RecipeDetailViewController? Xcode doesn’t know what it is.

Let’s talk about the second error first. In RecipeBookViewController, it has no idea about RecipeDetailViewController. In Objective C, you use the “#import” directive to import the header file of other class. By importing the header file of “RecipeDetailViewController”, RecipeBookViewController can access the properties and methods of the detail view controller. Place the following code at the very beginning to fix the error:

1
#import "RecipeDetailViewController.h"

Regarding the first error, you should know how to fix it. This is similar to the Label UI element we discussed earlier. There should be a corresponding tableView variable that connects with the UI element.

So, in the RecipeBookViewController.h, add the following code before “@end”:

1
@property (nonatomic, strong) IBOutlet UITableView *tableView;

For the RecipeBookViewController.m, add the synthesis directive to tell the compiler to generate the accessor methods for the tableView variable.

1
2
3
4
5
@implementation RecipeBookViewController {
    NSArray *recipes;
}

@synthesize tableView; // Add this line of code

Lastly, go back to the Storyboards and link up the variable with the UI element. In the “Recipe Book View Controller”, hold the command key and click the view controller icon, drag it to the table view. Release both buttons and select “tableView”.

Establish connection with the tableView variable

Now, all the errors should be resolved. Let’s try to compile and run the app. This time, your app should work as expected. Try to select any recipe and the detail view should display the name of the selected item.

From:http://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/

iphone dev 入门实例2:Pass Data Between View Controllers using segue的更多相关文章

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

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

  2. 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 ...

  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 入门实例3:Delete a Row from UITableView

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

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

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

  7. 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 ...

  8. 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 ...

  9. 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 t ...

随机推荐

  1. C++ Primer : 第十二章 : 动态内存之shared_ptr类实例:StrBlob类

    StrBlob是一个管理string的类,借助标准库容器vector,以及动态内存管理类shared_ptr,我们将vector保存在动态内存里,这样就能在多个对象之间共享内存. 定义StrBlob类 ...

  2. AtCoder Regular Contest 061

    AtCoder Regular Contest 061 C.Many Formulas 题意 给长度不超过\(10\)且由\(0\)到\(9\)数字组成的串S. 可以在两数字间放\(+\)号. 求所有 ...

  3. HDU 5234 Happy birthday --- 三维01背包

    HDU 5234 题目大意:给定n,m,k,以及n*m(n行m列)个数,k为背包容量,从(1,1)开始只能往下走或往右走,求到达(m,n)时能获得的最大价值 解题思路:dp[i][j][k]表示在位置 ...

  4. POJ2284 That Nice Euler Circuit (欧拉公式)(计算几何 线段相交问题)

                                                          That Nice Euler Circuit Time Limit: 3000MS   M ...

  5. IOS开发之SWIFT进阶部分

    概述 上一篇文章<iOS开发系列--Swift语言> 中对Swift的语法特点以及它和C.ObjC等其他语言的用法区别进行了介绍.当然,这只是Swift的入门基础,但是仅仅了解这些对于使用 ...

  6. 【P1203】买花

    我先在已经弱到连高精乘单精都能写错的地步了QAQ 原题: 求一个小于等于N的数M,使得phi(M)/M最小,其中phi(M)是与M互质且比M小的数的个数.例如phi(4)=2,因为1,3和4互质. N ...

  7. C#编写的windows程序随系统启动

    url:http://www.cnblogs.com/emanlee/archive/2009/08/31/1557380.html 设置某程序随系统启动自动运行,取消自动运行. 使用到using M ...

  8. kuangbin_ShortPath R (HDU 4370)

    出题人真是脑洞堪比黑洞 (然后自己也被吸进去了 理解一遍题意 三个条件可以转化为 1的出度是1, n的入度是1, 2~n-1的出度等于入度 不难发现1-n的最短路符合题意 然而其实还有另一种情况 1为 ...

  9. kuangbin_ShortPath G (POJ 1502)

    尽管题目很长 写的很玄乎 让我理解了半天 但是事实上就是个模板题啊摔 一发水过不解释 #include <iostream> #include <string> #includ ...

  10. ExtJS参考手册

    ExtJS是一个用javascript写的,主要用于创建前端用户界面,是一个与后台技术无关的前端ajax框架.因此,可以把ExtJS用在.Net.Java.Php等各种开发语言开发的应用中.ExtJs ...