淺談Objective-C協(xié)議和委托
Objective-C協(xié)議和委托是本文呢要介紹的內(nèi)容,主要介紹了Objective-C中協(xié)議和委托的方式,通過實例講解讓我們更快更方便的去學(xué)習(xí)Objective-C,先來看詳細內(nèi)容。
protocol-協(xié)議,就是使用了這個協(xié)議后就要按照這個協(xié)議來辦事,協(xié)議要求實現(xiàn)的方法就一定要實現(xiàn)。
delegate-委托,顧名思義就是委托別人辦事,就是當一件事情發(fā)生后,自己不處理,讓別人來處理。
當一個A view 里面包含了B view
b view需要修改a view界面,那么這個時候就需要用到委托了。
需要幾個步驟
1、首先定一個協(xié)議
2、a view實現(xiàn)協(xié)議中的方法
3、b view設(shè)置一個委托變量
4、把b view的委托變量設(shè)置成a view,意思就是 ,b view委托a view辦事情。
5、事件發(fā)生后,用委托變量調(diào)用a view中的協(xié)議方法
例子:
- B_View.h:
 - @protocol UIBViewDelegate <NSObject>
 - @optional
 - - (void)ontouch:(UIScrollView *)scrollView; //聲明協(xié)議方法
 - @end
 - @interface BView : UIScrollView<UIScrollViewDelegate>
 - {
 - id< UIBViewDelegate > _touchdelegate; //設(shè)置委托變量
 - }
 - @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]; //調(diào)用協(xié)議委托
 - }
 - @end
 - A_View.h:
 - @interface AViewController : UIViewController < UIBViewDelegate >
 - {
 - BView *m_BView;
 - }
 - @end
 - A_View.mm:
 - - (void)viewWillAppear:(BOOL)animated
 - {
 - m_BView._touchdelegate = self; //設(shè)置委托
 - [self.view addSubview: m_BView];
 - }
 - - (void)ontouch:(UIScrollView *)scrollView
 - {
 - //實現(xiàn)協(xié)議
 - }
 
小結(jié):淺談Objective-C協(xié)議和委托的內(nèi)容介紹完了,希望本文對你有所幫助!















 
 
 
 
 
 
 