Objective-C ProtocolAndDelegateThis is the content to be introduced in this article.Objective-CMediumProtocolAndDelegateThrough examples, we can learn more quickly and conveniently.Objective-CFirst, let's look at the details.
Protocol-ProtocolThat is, after using this agreement, we must follow this agreement, and the methods required by the Agreement must be implemented.
Delegate-DelegateAs the name suggests, it is to entrust others to do things, that is, when one thing happens, they will not handle it themselves and let others handle it.
When A view contains B view
B view needs to modify the view interface, so delegation is required at this time.
Several steps are required
1. First define an agreement
2. Methods of a view Implementation Protocol
3. B view sets a delegate variable.
4. Set the delegate variable of B view to a view, which means that B view delegates a view to do things.
5. After an event occurs, use the delegate variable to call the Protocol method in a view.
Example:
- B _View.h:
- @ Protocol UIBViewDelegate <NSObject>
- @ Optional
- -(Void) ontouch :( UIScrollView *) scrollView; // declares the Protocol method.
- @ End
-
- @ Interface BView: UIScrollView <UIScrollViewDelegate>
- {
- Id <UIBViewDelegate> _ touchdelegate; // sets the delegate variable.
- }
- @ 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]; // call protocol delegate
- }
- @ End
-
- A_View.h:
-
- @ Interface AViewController: UIViewController <UIBViewDelegate>
- {
- BView * m_BView;
- }
- @ End
-
- A_View.mm:
-
- -(Void) viewWillAppear :( BOOL) animated
- {
- M_BView. _ touchdelegate = self; // sets the delegate
- [Self. view addSubview: m_BView];
- }
-
- -(Void) ontouch :( UIScrollView *) scrollView
- {
- // Implementation Protocol
- }
Summary:Objective-C ProtocolAndDelegateI hope this article will help you!