淺談Objective-C協議和委托
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中的協議方法
例子:
- 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
- {
- //實現協議
- }
小結:淺談Objective-C協議和委托的內容介紹完了,希望本文對你有所幫助!