IOS委托机制

来源:互联网 发布:ug软件安装 编辑:程序博客网 时间:2024/05/21 01:45

一、名词解释

protocol:协议,用来定义对象的属性,行为和用于回调,使用了这个协议后就要按照这个协议来办事,协议要求实现的方法就一定要实现。

协议中有两个关键字@private和@optional,@private表示使用这个协议必须要写的方法,@optional表示可选的方法,用不到可以不写。

delegate:委托,顾名思义就是委托别人办事,就是当一件事情发生后,自己不处理,让别人来处理。

二、使用机制

当一个A view 里面包含了B view,而B view需要修改A view界面,那么这个时候就需要用到委托了。

使用委托的步骤:
1、在B view中定义一个协议和声明协议的方法:
  1. @protocol UIBViewDelegate <NSObject>  
  2. @optional  
  3. - (void)ontouch:(UIScrollView *)scrollView; //声明协议方法  
  4. @end 
2、在A view中实现协议的方法。
  1. - (void)ontouch:(UIScrollView *)scrollView  
  2. {  
  3. //这里实现协议  
  4. }  
3、在B view设置一个委托变
  1. @interface BView : UIScrollView<UIScrollViewDelegate>   
  2. {  
  3. id< UIBViewDelegate > _touchdelegate; //设置委托变量  
  4. }  
  5. @property(nonatomic,assign) id< UIBViewDelegate > _touchdelegate;   
  6. @end 
4、把B view的委托变量设置成A view,意思就是 ,B view委托A view办事情。

  1. @interface AViewController : UIViewController <UIBViewDelegate> 
5、当B view中的事件发生后,用委托变量调用A view中的协议方法

  1. - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event  
  2. {  
  3. [super touchesBegan:touches withEvent:event];
  4. //方法检查
  5. if(_touchdelegate!=nil && [_touchdelegate respondsToSelector: @selector(ontouch:) ] == true)   
  6. [_touchdelegate ontouch:self]; //调用协议委托  
三、完整代码

  1. B_View.h:  
  2. @protocol UIBViewDelegate <NSObject>  
  3. @optional  
  4. - (void)ontouch:(UIScrollView *)scrollView; //声明协议方法  
  5. @end  
  6. @interface BView : UIScrollView<UIScrollViewDelegate>   
  7. {  
  8. id< UIBViewDelegate > _touchdelegate; //设置委托变量  
  9. }  
  10. @property(nonatomic,assign) id< UIBViewDelegate > _touchdelegate;   
  11. @end  
  1. B_View.mm:  
  2. @synthesize _touchdelegate;  
  3. - (id)initWithFrame:(CGRect)frame {  
  4. if (self = [super initWithFrame:frame]) {  
  5. // Initialization code  
  6. _touchdelegate=nil;  
  7. }  
  8. return self;  
  9. }  
  10. - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event  
  11. {  
  12. [super touchesBegan:touches withEvent:event];if(_touchdelegate!=nil && [_touchdelegate respondsToSelector: @selector(ontouch:) ] == true)   
  13. [_touchdelegate ontouch:self]; //调用协议委托  
  14. }  
  15. @end 
  1. A_View.h:  
  2. @interface AViewController : UIViewController <UIBViewDelegate>  
  3. {  
  4. BView *m_BView;  
  5. }  
  6. @end 
  1. A_View.mm:  
  2. - (void)viewWillAppear:(BOOL)animated  
  3. {  
  4. m_BView._touchdelegate = self; //设置委托  
  5. [self.view addSubview: m_BView]; 
  6. }  
  7. - (void)ontouch:(UIScrollView *)scrollView  
  8. {  
  9. //实现协议 


0 0