IOS之代理(delegate)的开发模式

1.代理模式在ios开发使用的很多比如uitableview,uicollectioin的代理方式,用的太多,表面的意识就是,委托别人做事,帮助viewcontroller去解决一系列问题的,直接上代码了:

 

在ChilderViewController.h:

 #import <UIKit/UIKit.h>

 @protocol ChilderViewControllerDlegate <NSObject>

 -(void)getColor:(UIColor *)color;

 @end

 @interface ChilderViewController : UIViewController

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

 @end

 

在ChilderViewController.m:

#import "ChilderViewController.h"

 

@interface ChilderViewController ()

 

@end

 

@implementation ChilderViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 200, 50)];

    [button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];

    //    button.backgroundColor = [UIColor redColor];

    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [button setTitle:@"返回调用代理" forState:UIControlStateNormal];

    [self.view addSubview:button];

}

-(void)show {

    [self.delegate getColor:[UIColor redColor]];

    [self.navigationController popToRootViewControllerAnimated:YES];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated

}

在一个mainvccongtroller中push过去之后ChilderViewContrller,点击ChilderViewController中的按钮改变根视图的背景颜色:

MainViewController.m

#import "MainViewController.h"

#import "ChilderViewController.h"

 

@interface MainViewController ()<ChilderViewControllerDlegate>

 

@end

 

@implementation MainViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

-(void)getColor:(UIColor *)color{

 

    

    self.view.backgroundColor = color;

    NSLog(@"change color........");

}

 

- (IBAction)onClick:(id)sender {

 

    ChilderViewController *childerVC = [[ChilderViewController alloc]init];

    childerVC.delegate = self;

    [self.navigationController pushViewController:childerVC animated:YES];

    

}

 

 

 

 

 

你可能感兴趣的:(IOS之代理(delegate)的开发模式)