@UI初级之代理模式
在UI设计中,有一种方便的设计模式--代理模式,通常人们创建一种协议,然后在协议中会有协议特有的方法,这种时候就要设置代理来遵守协议,并且让代理来实现协议中的方法,这样就好比雇佣了一个帮手来帮助你实现和操作一些工作,可以有效的进行工程的操作和实现.
@举例创建一个协议
@class CustomView;//CustomView是新建的一个UIView的视图类
@protocol CustomViewDelegate <NSObject>
//下面是需要实现的协议方法
-(void)viewTouchBegan:(CustomView *)view;
-(void)viewTouchMove:(CustomView *)view;
-(void)viewTouchEnd:(CustomView *)view;
@end
//设置一个代理的属性,使代理delegate遵守协议CustomViewDelegate
@property (nonatomic,assign)id<CustomViewDelegate>delegate;
//以下为利用代理来实现协议方法(在一个视图控制器中定义的方法,利用代理协议)
-(void)viewTouchBegan:(CustomView *)view
{
NSLog(@"%s,%d",__FUNCTION__,__LINE__);
_testView.backgroundColor = [UIColor yellowColor];
}
-(void)viewTouchMove:(CustomView *)view
{
NSLog(@"%s,%d",__FUNCTION__,__LINE__);
_testView.backgroundColor = [UIColor greenColor];
}
-(void)viewTouchEnd:(CustomView *)view
{
NSLog(@"%s,%d",__FUNCTION__,__LINE__);
_testView.backgroundColor = [UIColor blackColor];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(viewTouchBegan:)]) {
[self.delegate viewTouchBegan:self];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(viewTouchMove:)]) {
[self.delegate viewTouchMove:self];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(viewTouchEnd:)]) {
[self.delegate viewTouchEnd:self];
}
}
注:NSLog(@"%s,%d",__FUNCTION__,__LINE__);是用来检测代理实现的过程
@实现检测代理过程的运行截图,图为点击了两次的结果