首页 > 代码库 > 简单的deletage(代理)模式
简单的deletage(代理)模式
delegate是iOS编程中的一种设计模式,它适用与让一个对象去检测自定义控件的各种状态。
我们可以用这个设计模式来让单继承的objective-c类表现出它父类之外类的特征.
代码如下: 一个类CustomView继承于NSObject,它加载在MainViewController上。这段代码的主要用途就是几种触摸事件
首先,先定义CustomView,在其头文件中定义代理CustomViewDelegate
同时声明3个方法
@protocol CustomViewDelegate <NSObject>
@optional //可选择性
//开始有关的状态:customView开始被触摸
-(void)customViewBeganTouch:(CustomView *)customView;
// customView 被move
-(void)customViewMoveTouch:(CustomView *)customView;
//customView 触摸结束
-(void)customViewEndedTouch:(CustomView *)customView;
@end
@interface CustomView : UIView
@property (nonatomic, assign) id<CustomViewDelegate> delegate;
@end
然后在CustomView.m中通知delegate执行的某个协议方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//通知delegate执行的某个协议方法
if ([_delegate respondsToSelector:@selector(customViewBeganTouch:)]) {
[_delegatecustomViewBeganTouch:self];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([_delegaterespondsToSelector:@selector(customViewMoveTouch:)]) {
[_delegatecustomViewMoveTouch:self];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([_delegaterespondsToSelector:@selector(customViewEndedTouch:)]) {
[_delegatecustomViewEndedTouch:self];
}
}
在这个时候,CustomView的事情做完了,可以简单的理解为封装完了,接下来就该处理MainViewController中的问题了
MainViewController只要在定义CustomView的时候指定其代理为自身,就可以执行了
这时候先要在MainViewController.h中导入CustomView的头文件
#import <UIKit/UIKit.h>
#import "CustomView.h"
@interface MainViewController : UIViewController<CustomViewDelegate>
@end
剩下的事情就在MainViewController.m中处理了
要先创建customView的对象,设置delegate
- (void)viewDidLoad
{
[superviewDidLoad];
//创建customView的对象,设置delegate
CustomView *customView = [[CustomView alloc]initWithFrame:CGRectMake(50, 50, 50, 50)];
customView.backgroundColor = [UIColorredColor];
[self.view addSubview:customView];
[customView release];
customView.delegate = self; // 设置代理(delegate)
}
最后实现功能
-(void)customViewBeganTouch:(CustomView *)customView
{
self.view.backgroundColor = [UIColorcolorWithRed:arc4random()%256/255.0green:arc4random()%256/255.0blue:arc4random()%256/255.0alpha:1.0];
}
-(void)customViewEndedTouch:(CustomView *)customView
{
customView.center = CGPointMake(arc4random()%321, arc4random()%481);
}
以上就是简单的代理模式了。