IOS之UIViewController执行返回操作并传递参数值的两种形式
IOS之UIViewController执行返回操作并传递参数值的两种方式
举个例子,第一个page(即UIViewController)显示天气,需要对所在地进行设置,这就需要跳转到第二个page,选择好所在地之后,将所在地信息(即返回参数)传回第一个page。
第一种:通过Delegate的Protocol
1.新建PassValueDelegate.h
#import <Foundation/Foundation.h> @protocol PassValueDelegate <NSObject> -(void)passValue:(NSString *)value; @end
2.在需要得到返回值的UIViewController.h添加对PassValueDelegate的实现
@interface IkrboyViewController6 : UIViewController<PassValueDelegate>
3.在UIViewController.m实现-(void)passValue的方法,即处理得到的返回值的事件
-(void)passValue:(NSString *)value{ NSLog(@"get backcall value=%@",value); }
4.在下一个UIViewController.h(即为上一个UIViewController提供返回数据)添加Delegate的参数
@property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;
5.在上一个UIViewController跳转到下一个UIViewController之前添加代码
//设置第二个窗口中的delegate为第一个窗口的self newViewController.delegate = self;
6.下一个UIViewController返回到上一个UIViewController的代码
self dismissViewControllerAnimated:YES completion:^{ //通过委托协议传值 [self.delegate passValue:@"ululong"]; }];
第二种:绑定Notification,利用userInfo参数
1.在第一个UIViewController的viewDidLoad添加注册RegisterCompletionNotification代码
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerCompletion:) name:@"RegisterCompletionNotification" object:nil];
2.别忘了解除·Notification
- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. [[NSNotificationCenter defaultCenter] removeObserver:self]; }
3.实现registCompletion方法
-(void)registerCompletion:(NSNotification*)notification { //接受notification的userInfo,可以把参数存进此变量 NSDictionary *theData = [notification userInfo]; NSString *username = [theData objectForKey:@"username"]; NSLog(@"username = %@",username); }
4.在下一个UIViewController的返回操作中添加代码
NSDictionary *dataDict = [NSDictionary dictionaryWithObject:@"MissA" forKey:@"username"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"RegisterCompletionNotification" object:nil userInfo:dataDict]; [self dismissViewControllerAnimated:YES completion:nil];