一、名词解释
protocol:协议,用来定义对象的属性,行为和用于回调,使用了这个协议后就要按照这个协议来办事,协议要求实现的方法就一定要实现。
协议中有两个关键字@private和@optional,@private表示使用这个协议必须要写的方法,@optional表示可选的方法,用不到可以不写。
delegate:委托,顾名思义就是委托别人办事,就是当一件事情发生后,自己不处理,让别人来处理。
二、使用机制
当一个A view 里面包含了B view,而B view需要修改A view界面,那么这个时候就需要用到委托了。
使用委托的步骤:
1、在B view中定义一个协议和声明协议的方法:
- @protocol UIBViewDelegate <NSObject>
- @optional
- - (void)ontouch:(UIScrollView *)scrollView; //声明协议方法
- @end
2、在A view中实现协议的方法。
- - (void)ontouch:(UIScrollView *)scrollView
- {
- //这里实现协议
- }
3、在B view设置一个委托变
- @interface BView : UIScrollView<UIScrollViewDelegate>
- {
- id< UIBViewDelegate > _touchdelegate; //设置委托变量
- }
- @property(nonatomic,assign) id< UIBViewDelegate > _touchdelegate;
- @end
- @interface AViewController : UIViewController <UIBViewDelegate>
- - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
- {
- [super touchesBegan:touches withEvent:event];
- //方法检查
- if(_touchdelegate!=nil && [_touchdelegate respondsToSelector: @selector(ontouch:) ] == true)
- [_touchdelegate ontouch:self]; //调用协议委托
- }
- B_View.h:
- @protocol UIBViewDelegate <NSObject>
- @optional
- - (void)ontouch:(UIScrollView *)scrollView; //声明协议方法
- @end
- @interface BView : UIScrollView<UIScrollViewDelegate>
- {
- id< UIBViewDelegate > _touchdelegate; //设置委托变量
- }
- @property(nonatomic,assign) id< UIBViewDelegate > _touchdelegate;
- @end
- B_View.mm:
- @synthesize _touchdelegate;
- - (id)initWithFrame:(CGRect)frame {
- if (self = [super initWithFrame:frame]) {
- // Initialization code
- _touchdelegate=nil;
- }
- return self;
- }
- - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
- {
- [super touchesBegan:touches withEvent:event];if(_touchdelegate!=nil && [_touchdelegate respondsToSelector: @selector(ontouch:) ] == true)
- [_touchdelegate ontouch:self]; //调用协议委托
- }
- @end
- A_View.h:
- @interface AViewController : UIViewController <UIBViewDelegate>
- {
- BView *m_BView;
- }
- @end
- A_View.mm:
- - (void)viewWillAppear:(BOOL)animated
- {
- m_BView._touchdelegate = self; //设置委托
- [self.view addSubview: m_BView];
- }
- - (void)ontouch:(UIScrollView *)scrollView
- {
- //实现协议
- }