#import <UIKit/UIKit.h> #import "SubViewController.h" @interface ViewController : UIViewController<SubViewControllerDelegate> @end
#import "ViewController.h" @interface ViewController () { SubViewController *_subViewController; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _subViewController = [[SubViewController alloc]init]; self.view.backgroundColor = [UIColor orangeColor]; _subViewController.delegate = self; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(10, 30,200 , 30); [btn setTitle:@"跳转到SubViewController" forState:UIControlStateNormal]; [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeSystem]; btn1.frame = CGRectMake(10, 100, 200, 30); [btn1 setTitle:@"让SubViewController 变色" forState:UIControlStateNormal]; [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn1 addTarget:self action:@selector(btn1Click) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn1]; // Do any additional setup after loading the view, typically from a nib. } -(void)btn1Click { _subViewController.view.backgroundColor = [UIColor redColor]; } -(void)btnClick { [self presentViewController:_subViewController animated:YES completion:^{ }]; } -(void)changeColoer { self.view.backgroundColor = [UIColor purpleColor]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
#import <UIKit/UIKit.h> @protocol SubViewControllerDelegate <NSObject> -(void)changeColoer; @end @interface SubViewController : UIViewController @property(nonatomic,weak)__weak id<SubViewControllerDelegate>delegate; @end
#import <UIKit/UIKit.h> @protocol SubViewControllerDelegate <NSObject> -(void)changeColoer; @end @interface SubViewController : UIViewController @property(nonatomic,weak)__weak id<SubViewControllerDelegate>delegate; @end
这个小demo中我建立了两个视图控制器,一个是ViewController还有一个是SubViewController
两个页面能够进行相互跳转
点击SubViewController 中的变色button能够将ViewController中的颜色改变
点击ViewController中的变色button也能够将SubView中的颜色改变
代理实质就是指针的传递