iOS中delegate的使用

一、首先介紹Protocol

1稼跳、協(xié)議protocol說明

protocol:定義公用的一套接口酪术,但不提供具體的實(shí)現(xiàn)方法。
協(xié)議約定可選擇實(shí)現(xiàn)的方法和必須實(shí)現(xiàn)的方法经瓷。

@required:必須實(shí)現(xiàn)的方法
@optional:可選是否實(shí)現(xiàn)的方法

2爆哑、協(xié)議protocol的使用

//創(chuàng)建協(xié)議文件protocolDelegate

//1.new file -->Objective-C File-->選擇Protocol,創(chuàng)建Protocol文件
//protocol文件只有.h文件舆吮,只聲明方法揭朝。
#import <Foundation/Foundation.h>

@protocol protocolDelegate <NSObject>
@required
//必須實(shí)現(xiàn)的方法
- (void)eat;
- (void)drink;

// 可選實(shí)現(xiàn)的方法
@optional
- (void)readBook;
- (void)writeCode;
@end

//創(chuàng)建student類和programmer類具體實(shí)現(xiàn)對應(yīng)方法

//2.創(chuàng)建student類
//Student.h
#import <Foundation/Foundation.h>
#import "protocolDelegate.h"

@interface Student : NSObject <protocolDelegate>

@end
//Student.m
#import "Student.h"

@implementation Student

- (void)eat {
    NSLog(@"%@",@"我是學(xué)生队贱,我必須得吃飯,我吃米飯");
}

- (void)drink {
    NSLog(@"%@",@"我是學(xué)生潭袱,我必須得喝水柱嫌,我喝飲料");
}

- (void)readBook {
    NSLog(@"%@",@"我是學(xué)生,我會讀書");
}

@end
//3.創(chuàng)建Programma類
//Programma.h
#import <Foundation/Foundation.h>
#import "protocolDelegate.h"

@interface Programmer : NSObject <protocolDelegate>

@end
//Programma.m
#import "Programmer.h"

@implementation Programmer
- (void)eat {
    NSLog(@"%@",@"我是工程師屯换,我必須得吃飯编丘,我吃火鍋");
}

- (void)drink {
    NSLog(@"%@",@"我是工程師,我必須得喝水趟径,我喝啤酒");
}

- (void)writeCode {
    NSLog(@"%@",@"我是工程師瘪吏,我會寫代碼");
}
@end

//調(diào)用方法

//在viewcontroller里調(diào)用
#import "ViewController.h"
#import "Student.h"
#import "Programmer.h"

@interface ViewController ()

@property (nonatomic, strong) Student       *student;
@property (nonatomic, strong) Programmer    *programmer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self dinerTogether];
}

// 聚餐
- (void)dinerTogether {
    [self eatTogether];
    [self drinkTogether];
    [self doMySelf];
}
- (void)eatTogether {
    if ([self.student respondsToSelector:@selector(eat)]) {
        [self.student eat];
    }
    if ([self.programmer respondsToSelector:@selector(eat)]) {
        [self.programmer eat];
    }

}
- (void)drinkTogether {
    if ([self.student respondsToSelector:@selector(drink)]) {
        [self.student drink];
    }
    if ([self.programmer respondsToSelector:@selector(drink)]) {
        [self.programmer drink];
    }

}
- (void)doMySelf {
    if ([self.student respondsToSelector:@selector(readBook)]) {
        [self.student readBook];
    }
    if ([self.programmer respondsToSelector:@selector(writeCode)]) {
        [self.programmer writeCode];
    }

}

#pragma mark - getter and setter

- (Student *)student {
    if (!_student) {
        _student = [[Student alloc] init];
    }
    return _student;
}
- (Programmer *)programmer {
    if (!_programmer) {
        _programmer = [[Programmer alloc] init];
    }
    return _programmer;
}

@end

注:一般多個類要實(shí)現(xiàn)共同的方法,又各自有自己要實(shí)現(xiàn)的方法時蜗巧,可使用Protocol

一掌眠、delegate簡介

代理設(shè)計模式,是iOS中一種消息傳遞的方式幕屹,由代理對象蓝丙、委托者、協(xié)議組成望拖。

  • 協(xié)議:用來指定代理可以做什么渺尘,必須做什么。
  • 代理:根據(jù)指定協(xié)議说敏,完成委托方需要實(shí)現(xiàn)的方法鸥跟。
  • 委托:根據(jù)指定協(xié)議,指定代理必須完成和可以完成方法盔沫。

二医咨、delegate的使用

1、傳值

//下一控制器傳值給上一控制器
//下一控制器NextViewController文件

//NextViewController.h文件

#import <UIKit/UIKit.h>
@protocol NextViewControllerDelegate <NSObject>
- (void)sendValue:(NSString *)string;
@end

@interface NextViewController : UIViewController
@property (nonatomic, weak) id<NextViewControllerDelegate> delegate;
@end

//NextViewController.m文件
#import "NextViewController.h"

@interface NextViewController ()
//創(chuàng)建一個TextField輸入要傳端值
@property (nonatomic, strong) UITextField *tf_sendValue;
//創(chuàng)建返回上一控制器的按鈕
@property (nonatomic, strong) UIButton *btn_backVc;
@end

@implementation NextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 添加TextField
    UITextField *tf_sendValue = [[UITextField alloc]init];
    tf_sendValue.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
    tf_sendValue.textAlignment = 1;
    tf_sendValue.placeholder = @"請輸入要傳遞的值";
    self.tf_sendValue = tf_sendValue;
    [self.view addSubview:tf_sendValue];
    
    // 添加返回上一控制器的按鈕
    UIButton *btn_backVc = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 35)];
    [btn_backVc setTitle:@"返回上一控制器" forState:UIControlStateNormal];
    [btn_backVc setBackgroundColor:[UIColor redColor]];
    btn_backVc.center = self.view.center;
    self.btn_backVc = btn_backVc;
    [self.view addSubview:btn_backVc];
    //添加點(diǎn)擊事件
    [self.btn_backVc addTarget:self action:@selector(clickBackBtn) forControlEvents:UIControlEventTouchUpInside];
}
- (void)clickBackBtn{

    [self.navigationController popViewControllerAnimated:YES];
    NSString *str = self.tf_sendValue.text;
    if (str.length>0) {
        
        if ([self.delegate respondsToSelector:@selector(sendValue:)]) {
            [self.delegate sendValue:str];
        }
    }
}
@end

//上一控制器遵循協(xié)議架诞,實(shí)現(xiàn)代理方法拟淮,獲取傳遞的值

//ViewController.m文件
#import "ViewController.h"
#import "NextViewController.h"
@interface ViewController ()<NextViewControllerDelegate>
//創(chuàng)建一個Label顯示下一界面?zhèn)鬟^來的值
@property (nonatomic, strong) UILabel *lb_showStr;
//創(chuàng)建push下一界面按鈕
@property (nonatomic, strong) UIButton *btn_nextVc;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"第一個控制器";
    self.view.backgroundColor = [UIColor whiteColor];

    // 添加lb_showStr
    UILabel *lb_showStr = [[UILabel alloc]init];
    lb_showStr.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
    lb_showStr.textAlignment = NSTextAlignmentCenter;
    lb_showStr.text = @"顯示下一界面的傳值";
    self.lb_showStr = lb_showStr;
    [self.view addSubview:lb_showStr];
    // 添加push下一控制器按鈕
    UIButton *btn_nextVc = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 35)];
    [btn_nextVc setTitle:@"push下一界面" forState:UIControlStateNormal];
    [btn_nextVc setBackgroundColor:[UIColor redColor]];
    btn_nextVc.center = self.view.center;
    self.btn_nextVc = btn_nextVc;
    [self.view addSubview:btn_nextVc];
    //添加點(diǎn)擊事件
    [self.btn_nextVc addTarget:self action:@selector(clickPushBtn) forControlEvents:UIControlEventTouchUpInside];
}
- (void)clickPushBtn{
    NextViewController *nextVc = [[NextViewController alloc]init];
    [self.navigationController pushViewController:nextVc animated:YES];
    nextVc.delegate = self;
}
- (void)sendValue:(NSString *)string{
    self.lb_showStr.text = string;
}
@end

2、傳遞事件

//點(diǎn)擊自定義view谴忧,傳遞view點(diǎn)擊事件

//1.MyView.h
#import <UIKit/UIKit.h>

@protocol MyViewDelegate <NSObject>
- (void)myViewDelegateFunc;

@end

@interface MyView : UIView

//聲明代理屬性
@property (nonatomic, weak) id<MyViewDelegate> myViewDelegate;

@end

//2.MyView.m
#import "MyView.h"

@implementation MyView

//點(diǎn)擊view很泊,響應(yīng)代理方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    if ([_myViewDelegate respondsToSelector:@selector(myViewDelegateFunc)]) {
        [_myViewDelegate myViewDelegateFunc];
    }
}
@end

//實(shí)現(xiàn)代理方法

#import "ViewController.h"
#import "MyView.h"

@interface ViewController ()<MyViewDelegate>
@property (nonatomic, strong) MyView *myView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    MyView *myView = [[MyView alloc]init];
    myView.myViewDelegate = self;
    self.myView = myView;
    myView.backgroundColor = [UIColor redColor];
    myView.frame = CGRectMake(100, 100, 100, 100);
    myView.center = self.view.center;
    myView.userInteractionEnabled = YES;
    
    [self.view addSubview:self.myView];
}
#pragma mark - myViewDelegate代理方法
- (void)myViewDelegateFunc{
    NSLog(@"myViewDelegate的代理 點(diǎn)擊view");
}
@end

注:代理實(shí)現(xiàn)了不同視圖之間的數(shù)據(jù)交互,只有某一事件觸發(fā)才會被調(diào)用沾谓。在使用代理時委造,代理者要遵循代理,設(shè)置代理均驶,實(shí)現(xiàn)代理方法争涌。只有設(shè)置了代理,才能調(diào)用代理方法辣恋。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末亮垫,一起剝皮案震驚了整個濱河市模软,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌饮潦,老刑警劉巖燃异,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異继蜡,居然都是意外死亡回俐,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門稀并,熙熙樓的掌柜王于貴愁眉苦臉地迎上來仅颇,“玉大人,你說我怎么就攤上這事碘举⊥撸” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵引颈,是天一觀的道長耕皮。 經(jīng)常有香客問我,道長蝙场,這世上最難降的妖魔是什么凌停? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮售滤,結(jié)果婚禮上罚拟,老公的妹妹穿的比我還像新娘。我一直安慰自己完箩,他們只是感情好赐俗,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著嗜憔,像睡著了一般秃励。 火紅的嫁衣襯著肌膚如雪氏仗。 梳的紋絲不亂的頭發(fā)上吉捶,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天,我揣著相機(jī)與錄音皆尔,去河邊找鬼呐舔。 笑死,一個胖子當(dāng)著我的面吹牛慷蠕,可吹牛的內(nèi)容都是我干的珊拼。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼流炕,長吁一口氣:“原來是場噩夢啊……” “哼澎现!你這毒婦竟也來了仅胞?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤剑辫,失蹤者是張志新(化名)和其女友劉穎干旧,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體妹蔽,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡椎眯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了胳岂。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片编整。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖乳丰,靈堂內(nèi)的尸體忽然破棺而出掌测,到底是詐尸還是另有隱情,我是刑警寧澤成艘,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布赏半,位于F島的核電站,受9級特大地震影響淆两,放射性物質(zhì)發(fā)生泄漏断箫。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一秋冰、第九天 我趴在偏房一處隱蔽的房頂上張望仲义。 院中可真熱鬧,春花似錦剑勾、人聲如沸埃撵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽暂刘。三九已至,卻和暖如春捂刺,著一層夾襖步出監(jiān)牢的瞬間谣拣,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工族展, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留森缠,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓仪缸,卻偏偏與公主長得像贵涵,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子怔毛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容