比target-action更为常用的是delegate,下面是如何定义一个协议:
#TouchView.h
#import <UIKit/UIKit.h>
// 1.以前在OC阶段学习Delegate时 涉及到几个方面?
// 三方: 委托方 代理方 协议
// 2.如何定义一个协议?
// 协议指的是一堆方法的声明(OC笔试题)
#warning 1.定义协议
@class TouchView;
@protocol TouchViewDelegate <NSObject>
@optional
// touchView开始被点击
- (void)touchViewBeginTouched:(TouchView *)touchView;
// touchView结束被点击
- (void)touchViewEndTouched:(TouchView *)touchView;
@end
@interface TouchView : UIView
#warning 2.给外界提供设置delegate属性的接口
// 在定义Delegate属性时 需要使用assign关键字 防止产生循环引用
@property(nonatomic,assign)id<TouchViewDelegate>delegate;
@end
#TouchView.m
#import "TouchView.h"
@implementation TouchView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
#warning 6.在对应的时间点让Delegate去执行协议当中对应的方法.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_delegate && [_delegate respondsToSelector:@selector(touchViewBeginTouched:)])
{
[_delegate touchViewBeginTouched:self];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_delegate && [_delegate respondsToSelector:@selector(touchViewEndTouched:)])
{
[_delegate touchViewEndTouched:self];
}
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
}
#RootViewController.m
#import "RootViewController.h"
#import "TouchView.h"
#warning 4.接收协议
@interface RootViewController ()<TouchViewDelegate>
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 创建一个TouchView实例对象 并且设置delegate
TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
touchView.backgroundColor = [UIColor cyanColor];
#warning 3.给delegate属性赋值.
touchView.delegate = self;
[self.view addSubview:touchView];
[touchView release];
}
#warning 5.实现协议中的方法
#pragma mark - TouchViewDelegate
// 3.assign ==> 循环引用 为什么会存在循环引用问题?
// 循环引用是指两个对象互相retain对方(你中有我,我中有你)
//-(void)touchViewBeginTouched:(TouchView *)touchView
//{
// self.view.backgroundColor = [UIColor yellowColor];
//}
-(void)touchViewEndTouched:(TouchView *)touchView
{
NSLog(@"haha");
}