代理:
一.课件定义:为其他对象提供一种代理,以控制对这个对象的访问。
理解定义:代理就是为控制器中的某一控件提供一些其实现不了的方法,用于达到控件想要做的事情
二.具体DEMO
我们首先要声明一个代理方法(及协议)
#import <Foundation/Foundation.h>
@class tapView;
@protocol TapImageViewDelegate <NSObject>
-(void)tapImageViewClick:(tapView *)tapImgView;
@end
然后在控制器的控件类里将代理声明出来
.h文件:声明
@interface tapView : UIView
@property (nonatomic, strong) UIImageView * ima;
@property (nonatomic, weak) id <TapImageViewDelegate> delegate;
@end
.m文件:判断代理是否有这个方法,如果有则将控件类对象作为参数传给代理方法,并调用代理方法
@implementation tapView
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
_ima = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
_ima.userInteractionEnabled = YES;
[self addSubview:_ima];
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(change:)];
[tap setNumberOfTapsRequired:1];
[tap setNumberOfTouchesRequired:1];
[_ima addGestureRecognizer:tap];
}
return self;
}
- (void) change:(UITapGestureRecognizer *)sender
{
if ([_delegate respondsToSelector:@selector(tapImageViewClick:)])
{
[_delegate tapImageViewClick:self];
}
}
在控制器.m文件中,让控件类的类对象遵循自定义代理,自定义代理在.m文件中实现
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor =[UIColor whiteColor];
for (int i = 0; i < 3 ; i ++)
{
tapView * imageV = [[tapView alloc] initWithFrame:CGRectMake(i * 80, 50, 80, 80)];
imageV.delegate = self;
imageV.ima.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i + 1]];
[self.view addSubview:imageV];
}
}
//代理方法
-(void)tapImageViewClick:(tapView *)tapImgView
{
UIImageView * backimage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
backimage.image = tapImgView.ima.image;
[self.view addSubview:backimage];
}
程序做的顺序:先走控制器中的遵循代理,当点击事件发生后则走控件累的判断代理,在判断代理中调用控制器的实现代理方法,实现代理功能,达到控件想要达到的目的