iOS-delegate(代理/委托)

關(guān)于delegate的理解:是一種設(shè)計(jì)模式即代理模式,可以去參考中介找房案例來理解代理模式,說一下個人的理解吧:我理解的代理模式就是我需要做一件事但是我又沒有時間或者有一部分條件并不具備,所以我需要別人來完成,而我需要告訴他我要做什么,至于如何讓完成是他的事情

代理最常用的的用法就是逆向傳值,下面通過一個小demo來看一下具體怎么用

實(shí)現(xiàn)的功能:我有兩個頁面,我先當(dāng)前VC: MeViewController 通過按鈕跳轉(zhuǎn)到下一個VC:TestViewController,該VC上面三個按鈕,每當(dāng)我點(diǎn)擊一個按鈕是退回到上一個VC,并且在 VC:?MeViewController 的label上顯示我點(diǎn)擊的按鈕是第幾個,即將我點(diǎn)擊的按鈕的值傳遞給上一個界面。

代碼實(shí)現(xiàn):

1.創(chuàng)建協(xié)議

//import "TestViewController.h":

@protocol TestViewControllerDelegate <NSObject>

// 讓協(xié)議方法帶參傳值

/**傳遞的值*/

- (void) showMeTarget:(NSInteger ) value;

@end

2.聲明委托變量

//import "TestViewController.h":

@interface TestViewController : UIViewController

@property (nonatomic, weak) id <TestViewControllerDelegate> delegate;

@end

至于為啥用weak 以后說到內(nèi)存管理再說

3.設(shè)置代理 因?yàn)槲沂窃贛eViewController里面跳轉(zhuǎn)的時候設(shè)置的,所以在MeViewController.h中

// #import "MeViewController.h"

- (void)jumpButtonDidClick {

? ? TestViewController *vc = [[TestViewController alloc]init];

? ? vc.title = @"跳轉(zhuǎn)頁面";

? ? vc.delegate = self;

? ? [self.navigationController pushViewController:vc animated:YES];

}

4.利用委托變量來調(diào)用協(xié)議方法,也就是將值傳遞過去讓代理者開始執(zhí)行協(xié)議

//import "TestViewController.h":

- (void) buttonDidClick:(UIButton *)btn {

? ? if([self.delegate respondsToSelector:@selector(showMeTarget:)])? ?{

? ? ? ? [self.delegate showMeTarget:btn.tag];

? ? }

? ? [self.navigationController popViewControllerAnimated:YES];

}

5.在代理MeViewController中遵守協(xié)議

@interface MeViewController ()<TestViewControllerDelegate,NSURLSessionDataDelegate>

@property (nonatomic,strong) UIButton *jumpButton;

@property (nonatomic,strong)UILabel *label;

@end

6.代理實(shí)現(xiàn)協(xié)議方法

- (void)showMeTarget:(NSInteger)value?{

? ? self.label.text = [NSString stringWithFormat:@"點(diǎn)擊了第%ld個按鈕",value];

}

嗯,看一下效果:


為作跳轉(zhuǎn)前的MeViewController


按鈕頁面


傳值完成
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容