iOS學習筆記-----使用代理(Delegate)的頁面傳值

前言:

因爲Object-C是不支持多繼承的,所以很多時候都是用Protocol(協議)來代替。Protocol(協議)只能定義公用的一套接口,但不能提供具體的實現方法。也就是說,它只告訴你要做什麼,但具體怎麼做,它不關心。

當一個類要使用某一個Protocol(協議)時,都必須要遵守協議。比如有些必要實現的方法,你沒有去實現,那麼編譯器就會報警告,來提醒你沒有遵守××協議。注意,我這裏說的是警告,而不是錯誤。對的,就算你不實現那些“必要實現”的方法,程序也是能運行的,只不過多了些警告。

Protocol(協議)的作用:

1. 定義一套公用的接口(Public)

@required:必須實現的方法
@optional:可選 實現的方法(可以全部都不實現)

2. 委託代理(Delegate)傳值:

它本身是一個設計模式,它的意思是委託別人去做某事。

比如:兩個類之間的傳值,類A調用類B的方法,類B在執行過程中遇到問題通知類A,這時候我們需要用到代理(Delegate)。

又比如:控制器(Controller)與控制器(Controller)之間的傳值,從C1跳轉到C2,再從C2返回到C1時需要通知C1更新UI或者是做其它的事情,這時候我們就用到了代理(Delegate)傳值。

3.使用Delegate頁面傳值

在寫代碼之前,先確定一下要實現的功能:

VCA:
VCA

VCB:
VCB
- 視圖從視圖控制器A跳轉到視圖控制器B
- 將視圖控制器B上textField的值傳遞給視圖控制器A的Label.

然後再思考一下協議的寫法.

在被彈出的VC(也就是VCB)中定義delegate,在彈出VC(也就是VCA)中實現該代理.

下面來看一下代碼:

1.在VCB中新建一個協議,協議名一般爲:類名+delegate
並且設置代理屬性

VCB.h文件


#import <UIKit/UIKit.h>

@protocol ViewControllerBDelegate <NSObject>

- (void)sendValue:(NSString *)string;

@end


@interface ViewControllerB : UIViewController

// 委託代理,代理一般需使用弱引用(weak)
@property(nonatomic, weak) id<ViewControllerBDelegate>delegate;

@end

2.在VCA中籤署協議

VCA.h文件

#import <UIKit/UIKit.h>
#import "ViewControllerB.h"

@interface ViewController : UIViewController <ViewControllerBDelegate>


@end

3.在VCA中實現協議方法,並設置VCB的代理

VCA.m文件


#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation ViewController

//跳轉按鈕事件
- (IBAction)buttonAction:(UIButton *)sender {

    ViewControllerB *vcB = [[ViewControllerB alloc] init];

    //設置vcB的代理
    vcB.delegate = self;

    //跳轉到vcB
    [self.navigationController pushViewController:vcB animated:YES];


}
//實現協議方法
- (void)sendValue:(NSString *)string {

    _label.text = string;

}

@end

4.在VCB中調用代理方法

VCB.m文件

#import "ViewControllerB.h"

@interface ViewControllerB ()
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ViewControllerB

//back按鈕點擊事件
- (IBAction)buttonAction:(UIButton *)sender {

    //調用代理方法
    [_delegate sendValue:_textField.text];
    //跳轉回vcA
    [self.navigationController popToRootViewControllerAnimated:YES];

}


@end

小結:

這樣寫的好處是:VCB中不需要關聯VCA,就能夠實現值的傳遞.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章