Segue传递数据

来源:互联网 发布:mac看不到隐藏文件 编辑:程序博客网 时间:2024/06/16 21:07

我们在使用Segue进行跳转的时候,往往需要传递一些数据,我们在下面的方法中进行数据传递的准备工作:

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

此方法包含两个参数:

  • segue:跳转的Segue,其中包含跳转的源Controller和目标Controller,我们可以获取到这两个controller的对象,并进行进一步操作。
  • sender:触发这个Segue的对象。

下面进行实例演示:
1. 创建一个Single View Application,在storyboard中添加一个View Controller,然后创建一个类,命名为SecondViewController,将这个类与新添加的View Controller关联起来。
2. 在第一个ViewController页面上添加一个button,并为此button添加一个segue,指向第二个ViewController。将这个Segue的identifier设置为”passdatasegue”。
3. 在SecondViewController的页面上添加一个label,并为其创建一个IBOutlet,名字为secondLabel,前三步效果如下图所示:
这里写图片描述
4. 在ViewController.m中添加如下代码:

#import "SecondViewController.h"...- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{    if ([segue.identifier isEqualToString:@"passdatasegue"]) {        NSString *dataPassed = @"This is the data";        SecondViewController *secVC = [segue destinationViewController];        //将Key为dataFromVC的值设为dataPassed,这里的"dataFromVC",代表SecondViewContrller中的同名属性,因此需要在SecondViewController中创建这个属性        [secVC setValue:dataPassed forKey:@"dataFromVC"];    }}
  1. 在SecondViewController中添加如下代码:
@interface SecondViewController ()...@property (strong, nonatomic) NSString *dataFromVC;@end...- (void)viewDidLoad {    [super viewDidLoad];    _secondLabel.text = [self valueForKey:@"dataFromVC"];}...

运行程序,效果如下所示:
这里写图片描述

阅读全文
0 0
原创粉丝点击