通过代理 delegate
VCSecond。h
#import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN //定义一个协议 视图控制器二协议 @protocol VCSecondDelegate <NSObject> //定义一个协议函数,改变背景颜色 -(void) changecolor:(UIColor*) color; @end @interface VCSecond : UIViewController // 定义一个代理对象 //代理对象执行协议函数 //通过代理对象实现协议函数 达到代理对象改变本身属性的目的 //代理对象一定要实现代理协议 @property (assign,nonatomic)NSInteger tag; @property (assign,nonatomic)id<VCSecondDelegate> delegate; @end
VCSecond。m
#import "VCSecond.h" @interface VCSecond () @end @implementation VCSecond - (void)viewDidLoad { [super viewDidLoad]; UIBarButtonItem* btn= [[UIBarButtonItem alloc] initWithTitle:@"change color" style:UIBarButtonItemStyleDone target:self action:@selector(pressesChanged)]; self.navigationItem.rightBarButtonItem=btn; } -(void)pressesChanged{ // 代理对象调用事件操作 [_delegate changecolor:[UIColor redColor]]; } @end
VCFirst。h
#import <UIKit/UIKit.h> #import "VCSecond.h" NS_ASSUME_NONNULL_BEGIN @interface VCFirst : UIViewController -(void) changecolor:(UIColor*) color; @end NS_ASSUME_NONNULL_END
#import <UIKit/UIKit.h> #import "VCSecond.h" NS_ASSUME_NONNULL_BEGIN @interface VCFirst : UIViewController -(void) changecolor:(UIColor*) color; @end NS_ASSUME_NONNULL_END
VCFirst。m
#import "VCFirst.h" #import "VCSecond.h" @interface VCFirst () @end @implementation VCFirst - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } -(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { VCSecond* vc= [[VCSecond alloc] init]; // 将当前控制器作为代理对象赋值 vc.delegate=self; vc.view.backgroundColor = [UIColor orangeColor]; [self.navigationController pushViewController:vc animated:YES]; } -(void)changecolor:(UIColor *)color { self.view.backgroundColor = color; } @end