IOS之代理(delegate)的開發模式

來源:互聯網
上載者:User

標籤:

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)的開發模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.