//在RootViewController.h里面遵守协议
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController
@end
-----------------------------------<>-------------------------
//RootViewController.m
#import "RootViewController.h"
#import "TouchView.h"
@interface RootViewController ()<TouchViewDelegate>{
TouchView *touch;
}
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
touch = [[TouchView alloc] initWithFrame:CGRectMake(10, 65, 100, 100)];
touch.backgroundColor = [UIColor redColor];
touch.delegate = self;
[self.view addSubview:touch];
[touch release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - TouchViewDelegate
-(void)canTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
touch.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255. green:arc4random() % 256 / 255. blue:arc4random() % 256 / 255. alpha:1.0];
}
@end
----------------------------<自己定义的TouchView, 继承于UIView>-----------------------------
#import <UIKit/UIKit.h>
@protocol TouchViewDelegate <NSObject>//制订协议, 协议名 : 类名 + delegate
-(void)canTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;//制定协议里面的方法
@end
@interface TouchView : UIView
@property (nonatomic, retain) id<TouchViewDelegate>delegate;
@end
----------------------------------------------<>-------------------------------------------
#import "TouchView.h"
@implementation TouchView
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//让代理执行本应该TouchView完成的方法
if ([_delegate respondsToSelector:@selector(canTouchesEnded:withEvent:)]) {
[_delegate canTouchesEnded:touches withEvent:event];//把参数传进来
}
// self.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255. green:arc4random() % 256 / 255. blue:arc4random() % 256 / 255. alpha:1.0];
}
@end