iOS之UIViewController执行返回操作并传递参数值的两种方式

来源:互联网 发布:书生空谈 知乎 编辑:程序博客网 时间:2024/04/28 14:56

举个例子,第一个page(即UIViewController)显示天气,需要对所在地进行设置,这就需要跳转到第二个page,选择好所在地之后,将所在地信息(即返回参数)传回第一个page。

第一种:通过Delegate的Protocol

1.新建PassValueDelegate.h

Cpp代码  收藏代码
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @protocol PassValueDelegate <NSObject>  
  4.   
  5. -(void)passValue:(NSString *)value;  
  6.   
  7. @end  

 2.在需要得到返回值的UIViewController.h添加对PassValueDelegate的实现

Cpp代码  收藏代码
  1. @interface IkrboyViewController6 : UIViewController<PassValueDelegate>  

 3.在UIViewController.m实现-(void)passValue的方法,即处理得到的返回值的事件

Cpp代码  收藏代码
  1. -(void)passValue:(NSString *)value{  
  2.     NSLog(@"get backcall value=%@",value);  
  3. }  

 4.在下一个UIViewController.h(即为上一个UIViewController提供返回数据)添加Delegate的参数

Cpp代码  收藏代码
  1. @property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;  

 5.在上一个UIViewController跳转到下一个UIViewController之前添加代码

Cpp代码  收藏代码
  1. //设置第二个窗口中的delegate为第一个窗口的self  
  2.     newViewController.delegate = self;  

 6.下一个UIViewController返回到上一个UIViewController的代码

Cpp代码  收藏代码
  1. self dismissViewControllerAnimated:YES completion:^{  
  2.             //通过委托协议传值  
  3.             [self.delegate passValue:@"ululong"];  
  4.     }];  

 

第二种:绑定Notification,利用userInfo参数

 1.在第一个UIViewController的viewDidLoad添加注册RegisterCompletionNotification代码

Cpp代码  收藏代码
  1. [[NSNotificationCenter defaultCenter] addObserver:self  
  2.                                              selector:@selector(registerCompletion:)  
  3.                                                  name:@"RegisterCompletionNotification"  
  4.                                                object:nil];  

 2.别忘了解除·Notification

Cpp代码  收藏代码
  1. - (void)didReceiveMemoryWarning  
  2. {  
  3.     [super didReceiveMemoryWarning];  
  4.     // Dispose of any resources that can be recreated.  
  5.     [[NSNotificationCenter defaultCenter] removeObserver:self];  
  6. }  

3.实现registCompletion方法

Cpp代码  收藏代码
  1. -(void)registerCompletion:(NSNotification*)notification {  
  2.     //接受notification的userInfo,可以把参数存进此变量  
  3.     NSDictionary *theData = [notification userInfo];  
  4.     NSString *username = [theData objectForKey:@"username"];  
  5.       
  6.     NSLog(@"username = %@",username);  
  7. }  

 4.在下一个UIViewController的返回操作中添加代码

Cpp代码  收藏代码
  1. NSDictionary *dataDict = [NSDictionary dictionaryWithObject:@"MissA"  
  2.                                                          forKey:@"username"];  
  3.     [[NSNotificationCenter defaultCenter]  
  4.      postNotificationName:@"RegisterCompletionNotification"  
  5.      object:nil  
  6.      userInfo:dataDict];  
  7.   
  8.       
  9.     [self dismissViewControllerAnimated:YES completion:nil];  
1 0
原创粉丝点击