在需要传值的页面的.h文件中先声明协议和代理方法(代理方法不唯一,可以多个)、设定一个代理人
#import <UIKit/UIKit.h>
#warning第一步 声明协议及代理方法
@protocol ChangeColorDelegate <NSObject>
- (void)changeColor;
@end
@interface AView : UIView
#warning第二步 设置代理人
@property (nonatomic, assign)id<ChangeColorDelegate>colorDelegate;
@end
在需要传值的页面的.m文件中
#warning第三步 执行代理方法 一定要写在触发方法里面 如果是按钮就写在点击按钮后触发的方法里
//对需要传值的页面的.m文件进行初始化,并且建立一个button,点击button进行代理传值
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(40, 100, 40, 40);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor yellowColor];
[self addSubview:button];
}
return self;
}
- (void)buttonAction:(UIButton *)button
{
//代理人执行代理方法必须写到所触发的方法里
[self.colorDelegate changeColor];
}
@end
#import <UIKit/UIKit.h>
#import "AView.h"
#warning 第四步 签订协议
@interface RootViewController : UIViewController <ChangeColorDelegate>
@property (nonatomic, retain) AView *aView;
@end
在被传值的页面的.m文件中指定代理人以及实现代理方法,内存问题不要忘记
#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)dealloc
{
[_aView release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor lightGrayColor];
self.aView = [[AView alloc]initWithFrame:CGRectMake(40, 40, 300, 300)];
self.aView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.aView];
[self.aView release];
#warning第五步 指定代理人
self.aView.colorDelegate = self;
}
#warning第六步 实现代理方法
- (void)changeColor
{
NSLog(@"有人点我了, 我要改你里面的东西");
self.view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end