Objective-C protocol and Delegation

Source: Internet
Author: User
Objective-c Protocol delegate implements Protocol-the Protocol. After using this protocol, you must follow this Protocol. The methods required by the Protocol must be implemented. Delegate delegate-delegation, as its name implies, is to entrust others to handle affairs, that is, when one thing happens, it will not be handled by others. When a view contains B view and B view needs to modify the View Interface, delegation is required. Steps 1 are required. First set a protocol Protocol 2. Method 3 in the implementation protocol of a view. B View sets a delegate variable limit 4. Set the delegate variable of B view to a view, which means that B view delegates a view to do things. Limit 5. After an event occurs, use the delegate variable to call the Protocol method in a view. Example: 
 B _view.h: Protocol @ 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];
Else if (_ touchdelegate! = Nil & [_ touchdelegate respondstoselector: @ selector (ontouch :)] = true)
[_ Touchdelegate ontouch: Self]; // call protocol delegate
}
@ End paia_view.h: audience @ 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];
Token}
-(Void) ontouch :( uiscrollview *) scrollview
{
// Implementation Protocol
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.