淺談Objective-C協議和委託

來源:互聯網
上載者:User

Objective-C協議委託是本文呢要介紹的內容,主要介紹了Objective-C協議委託的方式,通過執行個體講解讓我們更快更方便的去學習Objective-C,先來看詳細內容。

protocol-協議,就是使用了這個協議後就要按照這個協議來辦事,協議要求實現的方法就一定要實現。

delegate-委託,顧名思義就是委託別人辦事,就是當一件事情發生後,自己不處理,讓別人來處理。

當一個A view 裡麵包含了B view

b view需要修改a view介面,那麼這個時候就需要用到委託了。

需要幾個步驟

1、首先定一個協議

2、a view實現協議中的方法

3、b view設定一個委託變數

4、把b view的委託變數設定成a view,意思就是 ,b view委託a view辦事情。

5、事件發生後,用委託變數調用a view中的協議方法

例子:

 
  1. B_View.h:  
  2. @protocol UIBViewDelegate <NSObject> 
  3. @optional  
  4. - (void)ontouch:(UIScrollView *)scrollView; //聲明協議方法  
  5. @end  
  6.  
  7. @interface BView : UIScrollView<UIScrollViewDelegate>   
  8. {  
  9.  id< UIBViewDelegate > _touchdelegate; //設定委託變數  
  10. }  
  11. @property(nonatomic,assign) id< UIBViewDelegate > _touchdelegate;   
  12. @end  
  13.  
  14. B_View.mm:  
  15.  
  16. @synthesize _touchdelegate;  
  17. - (id)initWithFrame:(CGRect)frame {  
  18. if (self = [super initWithFrame:frame]) {  
  19.  // Initialization code  
  20.  _touchdelegate=nil;  
  21.  }  
  22.  return self;  
  23. }  
  24.  
  25. - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event  
  26. {  
  27.  [super touchesBegan:touches withEvent:event];  
  28.  if(_touchdelegate!=nil && [_touchdelegate respondsToSelector: @selector(ontouch:) ] == true)   
  29.   [_touchdelegate ontouch:self];  //調用協議委託  
  30. }  
  31. @end  
  32.  
  33. A_View.h:  
  34.  
  35. @interface AViewController : UIViewController < UIBViewDelegate > 
  36. {  
  37.  BView *m_BView;  
  38. }  
  39. @end  
  40.  
  41. A_View.mm:  
  42.  
  43. - (void)viewWillAppear:(BOOL)animated  
  44. {  
  45.  m_BView._touchdelegate = self; //設定委託  
  46.  [self.view addSubview: m_BView];  
  47. }  
  48.  
  49. - (void)ontouch:(UIScrollView *)scrollView  
  50. {  
  51.     //實現協議  

小結:淺談Objective-C協議委託的內容介紹完了,希望本文對你有所協助!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.