码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-01-22 13:48:30      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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)的开发模式

标签:

原文地址:http://www.cnblogs.com/zhufeng1994/p/5150702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!