本文共 2472 字,大约阅读时间需要 8 分钟。
ChildViewCongroller.h
// // ChildViewController.h // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import@protocol ChildDelegate -(void)changeColor:(UIColor *)color;@end @interface ChildViewController : UIViewController{}@property(assign,nonatomic)id ChildDelegate;@end
ChildVIewController.m
// // ChildViewController.m // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import "ChildViewController.h" @interface ChildViewController () @end @implementation ChildViewController- (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 { [_ChildDelegate changeColor:[UIColor redColor]]; [self.navigationController popToRootViewControllerAnimated:YES];}@end
在一个ViewController中去push出来ChildViewController。点击ChildViewController中的按钮改变根视图的背景色
ViewController.h// // ViewController.h // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import#import "ChildViewController.h" @interface ViewController : UIViewController - (IBAction)showChild:(id)sender;@end
ViewController.m
// // ViewController.m // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; }#pragma mark - ChildViewDelegate Mehtod-(void)changeColor:(UIColor *)color { self.view.backgroundColor =color; NSLog(@"change color.....");}- (IBAction)showChild:(id)sender { ChildViewController *child = [ChildViewController new]; child.ChildDelegate = self; [self.navigationController pushViewController:child animated:YES];}@end
这样通过代理就可以去实现。
转载地址:http://zwgfa.baihongyu.com/