创建一个类继承于UIView
.h中的步骤
// (1).声明一份协议
@protocol MyButtonDelegate <NSObject>
-(void)changeColor;
@end
@interface MyButton : UIView
(2).设置代理人的属性
@property(nonatomic, assign)id<MyButtonDelegate>delegate;
(3)在MyButton.m里
@end
.m里
// (3).重写触发方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
(4).设置代理人执行的方法
[self.delegate changeColor];
(5)在MainViewController.m里
}
MainViewController.m
@interface MainViewController ()<MyButtonDelegate>// 注意这个地方*****
(5).引完头文件之后 定义
MyButton *button = [[MyButton alloc]initWithFrame:CGRectMake(100, 100, 100, 40)];
button.backgroundColor = [UIColor yellowColor];
[self.view addSubview:button];
[button release];
(6).设置代理人
button.delegate = self;
-(void)changeColor
{
self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:arc4random() % 256 / 255.0];
}