您现在的位置是:首页 > 文章详情

iOS:切换视图时,反向传递数据方法二:代理

日期:2017-06-28点击:312

代理:

1、发送信息的控制器设置一个代理,并自定义一个代理的方法,用来传递数据

2、接受信息的控制器遵循发送信息的控制器的协议

3、接受信息的控制器设置发送信息的控制器的代理为自己self

4、接受信息的控制器实现协议中的方法,即接受数据

 

首先将控制器通过modal(push)方式联接,同时设置segue的identifier标识,因为这个identifier是与目的控制器唯一的识别的方式,最后再进行代码操作。

1、所有文件:

2、让FirstViewController关联自己的类ViewController(.h/.m)

3、让SecondViewController关联自己的类SecondViewController(.h/.m)

4、设置segue的identifier标识

 

具体代码如下:

FirstViewController控制器关联的ViewController类

复制代码
 1 #import "ViewController.h"  2 #import "SecondViewController.h"  3  4 @interface ViewController ()<SecondViewControllerDelegate>  5 @property (weak, nonatomic) IBOutlet UITextField *firstTextField;  6  7 @end  8  9 @implementation ViewController 10 11 - (void)viewDidLoad { 12  [super viewDidLoad]; 13 } 14 15 //重写该方法,视图切换时,自动调用 16 -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 17 { 18 if([segue.identifier isEqualToString:@"modal"]) 19  { 20 //获取目的控制器 21 SecondViewController *secondVC = segue.destinationViewController; 22 23 //正向传数据 24 secondVC.information = self.firstTextField.text; 25 26 //设置代理 27 secondVC.delegate = self; 28 29  } 30 } 31 32 #pragma mark -<SecondViewControllerDelegate> 33 //反向接受信息 34 -(void)FinishedInformation:(SecondViewController *)secondVC andinfo:(NSString *)infos 35 { 36 self.firstTextField.text = infos; 37 } 38 @end
复制代码

SecondViewController控制器关联的SeconViewController类

复制代码
 1 #import "SecondViewController.h"  2  3 @interface SecondViewController ()  4 @property (weak, nonatomic) IBOutlet UITextField *secondTextField;  5  6 @end  7  8 @implementation SecondViewController  9 //返回时的触发事件 10 - (IBAction)returnClicked:(UIBarButtonItem *)sender 11 { 12 //反向传递数据 13 [self.delegate FinishedInformation:self andinfo:self.secondTextField.text]; 14 15 //关闭模态窗口 16  [self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; 17 //[self dismissViewControllerAnimated:YES completion:nil]; 18 } 19 20 - (void)viewDidLoad { 21  [super viewDidLoad]; 22 23 // 显示文本框内容(接受传递过来的数据) 24 self.secondTextField.text = self.information; 25 } 26 27 @end
复制代码

 

程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!


本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/4808528.html,如需转载请自行联系原作者
原文链接:https://yq.aliyun.com/articles/362700
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章