iOS 代理反向傳值,ios代理反向傳
在上篇部落格 iOS代理協議 中,側重解析了委託代理協議的概念等,本文將側重於它們在開發中的應用。
假如我們有一個需求如下:介面A上面有一個button、一個label。從介面A跳轉到介面B,在介面B的輸入框中輸入字串,在介面A的label上顯示。這是一個典型的反向傳值的例子。這個例子的核心是:“在介面B的輸入框中輸入字串,在介面A的label上顯示”。也就是說:“介面B委託介面A顯示字串,頁面A是介面B的代理”。委託方向代理方反向傳值。
那麼我們該怎麼用代理設計模式來實現這個需求呢?
在程式中:
1.委託需要做的工作有:
1.1定義協議與方法
1.2聲明委託變數
1.3設定代理
1.4通過委託變數調用委託方法
2.代理需要做的工作有:
2.1遵循協議
2.2實現委託方法
在BViewController.h中:
//定義協議與方法@protocol DeliverDetegate <NSObject>- (void)setValue:(NSString *)string;@end@interface BViewController : UIViewController//聲明委託變數@property (weak,nonatomic) id<DeliverDetegate>B_Delegate;@end
在BViewController.m中:
@interface BViewController ()<UITextFieldDelegate>@property (strong, nonatomic) IBOutlet UITextField *DeliverText;@end
- (IBAction)DeliverAction:(id)sender { //通過委託變數調用委託方法 //輸入則顯示輸入的字串,未輸入顯示“未填寫” if (![_DeliverText.text isEqualToString:@""]) { NSLog(@"B向A發送資料%@",_DeliverText.text); //判斷代理中的方法是否被實現,避免未被實現代理的程式崩潰 if ([self.B_Delegate respondsToSelector:@selector(setValue:)]) { [self.B_Delegate setValue:_DeliverText.text]; } } else { NSLog(@"B向A發送資料%@",@"未填寫"); //判斷代理中的方法是否被實現,避免未被實現代理的程式崩潰 if ([self.B_Delegate respondsToSelector:@selector(setValue:)]) { [self.B_Delegate setValue:@"未填寫"]; } } [self.navigationController popViewControllerAnimated:YES];}
在AViewController.m中
#import "AViewController.h"#import "BViewController.h"@interface AViewController ()<DeliverDetegate>@property (strong, nonatomic) IBOutlet UILabel *TextLabel;@end
- (IBAction)ReceiveAction:(id)sender { //遵循協議 BViewController*BVC = [[BViewController alloc]init]; BVC.B_Delegate = self; [self.navigationController pushViewController:BVC animated:YES];}
//實現委託方法,即實現的setValue方法- (void)setValue:(NSString *)string{ NSLog(@"A接收到B資料%@",string); _TextLabel.text = string;}
最後的如下:
輸出日誌:
由於本文用的是XIB,省略了部分UI細節,附上本文的代碼連結:源碼。
哪裡寫的不好,望評論指點。謝過~