Storyboards Segue Tutorial: Pass Data Between View Controllers

This is the second article of our Storyboards series. In thefirst tutorial, we introduced the Storyboards, which is a friendly feature in Xcode for designing user interface. If you’ve followed the tutorial from start to end, you should already build a simple recipe app with navigation interface. But we left one thing that was not discussed: data passing between scenes (i.e. view controllers) with segue.

First, let’s take a quick look at what we’ve accomplished. Previously, we learnt to use Storyboards to build a few things:

  • Embedded a normal view controller in navigation controller
  • Created a table view and populate a list of recipes
  • Switched from one view controller to another view controller using Segue

And, this is the final deliverable. When the app is launched, it displays a list of recipes. Tap on any of them will bring you to another view, that supposes to display the details of recipes.

Receipe App With Detail Controller

Receipe App with Detail Controller

We didn’t implement the detail view which now shows a static label. So we’ll continue to work on this project and polish the app.

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

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

Storyboard New View Controller

Create New File in Xcode Project

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

Storyboard New ObjectiveC Class

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.

Storyboard New RecipeDetailViewController Class

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

Storyboard Change View Controller Class

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.

Storyboard Recipe Detail Link 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

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

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:

1
2
3
4
5
6
7
-  ( 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.

Storyboard prepareForSegue Error

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

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

Recipe App With Correct Detail View

Recipe App - Our Final Deliverable

What’s Coming Next?

Isn’t it easy to build an app with navigation interface? With the introduction of Storyboard, it significantly reduces the amount of code you need to deal with. Most importantly, the centralized Storyboard interface provides a high-level overview about the flow of the app. I hope these two tutorials gives you an idea about how Storyboard works and how you can make use of it to build your own app. Though the app we’ve created is simple and with an elementary UI, it elaborates the fundamental concept that you can base on it to build more complex app.

In the later tutorials, we’ll explore the static table cell and continue to make the app even better with tab controller. Stay tuned and make sure you leave us comment below if you have any questions.


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


先展示下效果 https://pan.quark.cn/s/e81b877737c1 Node.js 是一种基于 Chrome V8 引擎的 JavaScript 执行环境,它使开发者能够在服务器端执行 JavaScript 编程,显著促进了全栈开发的应用普及。 在 Node.js 的开发流程中,`node_modules` 文件夹用于存储所有依赖的模块,随着项目的进展,该文件夹可能会变得异常庞大,其中包含了众多可能已不再需要的文件和文件夹,这不仅会消耗大量的硬盘空间,还可能减慢项目的加载时间。 `ModClean 2.0` 正是为了应对这一挑战而设计的工具。 `ModClean` 是一款用于清理 `node_modules` 的软件,其核心功能是移除那些不再被使用的文件和文件夹,从而确保项目的整洁性和运行效率。 `ModClean 2.0` 是此工具的改进版本,在原有功能上增加了更多特性,从而提高了清理工作的效率和精确度。 在 `ModClean 2.0` 中,用户可以设置清理规则,例如排除特定的模块或文件类型,以防止误删重要文件。 该工具通常会保留项目所依赖的核心模块,但会移除测试、文档、示例代码等非运行时必需的部分。 通过这种方式,`ModClean` 能够协助开发者优化项目结构,减少不必要的依赖,加快项目的构建速度。 使用 `ModClean` 的步骤大致如下:1. 需要先安装 `ModClean`,在项目的根目录中执行以下命令: ``` npm install modclean -g ```2. 创建配置文件 `.modcleanrc.json` 或 `.modcleanrc.js`,设定希望清理的规则。 比如,可能需要忽略 `LICENSE` 文件或整个 `docs`...
2026最新微信在线AI客服系统源码 微信客服AI系统是一款基于PHP开发的智能客服解决方案,完美集成企业微信客服,为企业提供7×24小时智能客服服务。系统支持文本对话、图片分析、视频分析等多种交互方式,并具备完善的对话管理、人工转接、咨询提醒等高级功能。 核心功能 ### 1.  智能AI客服 #### 自动回复 - **上下文理解**:系统自动保存用户对话历史,AI能够理解上下文,提供连贯的对话体验 - **个性化配置**:可自定义系统提示词、最大输出长度等AI参数 #### 产品知识库集成 - **公司信息**:支持配置公司简介、官网、竞争对手等信息 - **产品列表**:可添加多个产品,包括产品名称、配置、价格、适用人群、特点等 - **常见问题FAQ**:预设常见问题及答案,AI优先使用知识库内容回答 - **促销活动**:支持配置当前优惠活动,AI会自动向用户推荐 ### 2. 多媒体支持 #### 图片分析 - 支持用户发送图片,AI自动分析图片内容 - 可结合文字描述,提供更精准的分析结果 - 支持常见图片格式:JPG、PNG、GIF、WebP等 #### 视频分析 - 支持用户发送视频,AI自动分析视频内容 - 视频文件自动保存到服务器,提供公网访问 - 支持常见视频格式:MP4、等 ### 3.  人工客服转接 #### 关键词触发 - **自定义关键词**:可配置多个转人工触发关键词(如:人工、客服、转人工等) - **自动转接**:用户消息包含关键词时,自动转接给指定人工客服 - **友好提示**:转接前向用户发送提示消息,提升用户体验 #### 一键介入功能 - **后台管理**:管理员可在对话管理页面查看所有对话记录 - **快速转接**:点击"一键介入"按钮,立即将用户转接给人工客服
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值