1. 程式人生 > >iOS 代理反向傳值

iOS 代理反向傳值

obj receive leg 輸出 1.4 方法 bsp control 需求

在上篇博客 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細節,附上本文的代碼鏈接:源碼。

哪裏寫的不好,望評論指點。謝過~

iOS 代理反向傳值