iOS之UIViewController執行返回操作並傳遞引數值的兩種方式
阿新 • • 發佈:2019-01-25
舉個例子,第一個page(即UIViewController)顯示天氣,需要對所在地進行設定,這就需要跳轉到第二個page,選擇好所在地之後,將所在地資訊(即返回引數)傳回第一個page。
第一種:通過Delegate的Protocol
1.新建PassValueDelegate.h
Cpp程式碼- #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的方法,即處理得到的返回值的事件
Cpp程式碼- -(void)passValue:(NSString *)value{
- NSLog(@"get backcall value=%@",value);
- }
4.在下一個UIViewController.h(即為上一個UIViewController提供返回資料)新增Delegate的引數
- @property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;
5.在上一個UIViewController跳轉到下一個UIViewController之前新增程式碼
Cpp程式碼- //設定第二個視窗中的delegate為第一個視窗的self
- newViewController.delegate = self;
6.下一個UIViewController返回到上一個UIViewController的程式碼
Cpp程式碼-
self dismissViewControllerAnimated:YES completion:^{
- //通過委託協議傳值
- [self.delegate passValue:@"ululong"];
- }];
第二種:繫結Notification,利用userInfo引數
1.在第一個UIViewController的viewDidLoad添加註冊RegisterCompletionNotification程式碼
Cpp程式碼- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(registerCompletion:)
- name:@"RegisterCompletionNotification"
- object:nil];
2.別忘了解除·Notification
Cpp程式碼- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
3.實現registCompletion方法
Cpp程式碼- -(void)registerCompletion:(NSNotification*)notification {
- //接受notification的userInfo,可以把引數存進此變數
- NSDictionary *theData = [notification userInfo];
- NSString *username = [theData objectForKey:@"username"];
- NSLog(@"username = %@",username);
- }
4.在下一個UIViewController的返回操作中新增程式碼
Cpp程式碼- NSDictionary *dataDict = [NSDictionary dictionaryWithObject:@"MissA"
- forKey:@"username"];
- [[NSNotificationCenter defaultCenter]
- postNotificationName:@"RegisterCompletionNotification"
- object:nil
- userInfo:dataDict];
- [self dismissViewControllerAnimated:YES completion:nil];