首页 > 代码库 > delegate 传值demo

delegate 传值demo

代理的一般使用场合为:

1.对象B的内部发生一些事,想通知A,比如B通知A改颜色;

2.对象A想监听对象B内部发生了什么事情;

3.对象B想在自己的方法内部调用对象A的某个方法,并且对象B不能对对象A有耦合依赖;(A遵守协议,执行代理方法)

4.对象B想传递数据给对象A;

……………………

以上情况,结果都一样:对象A是对象B的代理(delegete),即B.delegate = A,对象B让对象A作为它的代理,帮它去做事;

 

一个最简单的列子来说明delegate的简单使用:界面A push 界面B,然后界面B pop 界面A的时候改变界面A的颜色,即界面B返回传值给界面A;

界面A为 AViewController,界面B为 BViewController

 

AViewController.h

1 #import <UIKit/UIKit.h>2 #import "BViewController.h"3 4 @interface AViewController : UIViewController<ChangeColorDelegate>5 {6     BViewController *B;7 }8 @end

AViewController.m

 1 - (void)viewDidLoad 2 { 3    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 4     button.frame = CGRectMake(140, 100, 60, 30); 5     button.backgroundColor = [UIColor whiteColor]; 6     [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 7     button.layer.cornerRadius = 8.0; 8     [button setTitle:@"推出B" forState:UIControlStateNormal]; 9     [button addTarget:self10                action:@selector(buttonClick:)11     forControlEvents:UIControlEventTouchUpInside];12     [self.view addSubview:button];13     14     B = [[BViewController alloc] init];15     B.delegate = self;//遵守协议16 }17 18 - (void)buttonClick:(id)sender19 {20     [self.navigationController pushViewController:B animated:YES];21 }22 //协议方法23 - (void)changeViewBackGroundColor:(UIColor *)color24 {25     self.view.backgroundColor = color;26 }

 

BViewController.h

1 #import <UIKit/UIKit.h>
2 @protocol ChangeColorDelegate <NSObject>3 - (void)changeViewBackGroundColor:(UIColor *)color;//协议方法4 @end
5 @interface BViewController : UIViewController6 @property (nonatomic,retain)id<ChangeColorDelegate>delegate;7 @end

BViewController.m

 1 - (void)viewDidLoad 2 { 3     [super viewDidLoad]; 4     self.view.backgroundColor = [UIColor redColor]; 5     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 6     button.frame = CGRectMake(140, 100, 60, 30); 7     button.backgroundColor = [UIColor whiteColor]; 8     button.layer.cornerRadius = 8.0; 9     [button setTitle:@"变色" forState:UIControlStateNormal];10     [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];11     [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];12     [self.view addSubview:button];13 }14 - (void)buttonClick:(id)sender15 { 16 //    if ([self.delegate respondsToSelector:@selector(changeViewBackGroundColor:)]) {17 //        [self.delegate changeViewBackGroundColor:[UIColor colorWithRed:arc4random()%255/255.0f green:arc4random()%255/255.0f blue:arc4random()%255/255.0f alpha:1]];18 //    }19     //这样写和上面的是一个意思,不需要加判断更直接,但有时候还是需要加判断的20     [self.delegate changeViewBackGroundColor:[UIColor colorWithRed:arc4random()%255/255.0f green:arc4random()%255/255.0f blue:arc4random()%255/255.0f alpha:1]];21     [self.navigationController popViewControllerAnimated:YES];22 }

这样就实现了简单的代理传值

delegate 传值demo