UI target...action design mode

Source: Internet
Author: User

"High cohesion, low coupling" is the core idea of object-oriented programming.
Decoupling is achieved using target...action.
Where a target is needed to perform an action.
For example, define a MyButton class that inherits from UIView, allowing him to have a click method for the button.
The code is as follows:
Mybutton.h:

#import <UIKit/UIKit.h>@interface Mybutton : UIView//1.写一个自定义方法,把目标和对应动作传过来.- (void)addNewTarget:(id)target Action:(SEL)action;//2.定义两条属性.@property(nonatomicassign)id target;@property(nonatomicassign)SEL action;@end

MYBUTTON.M:

#import "Mybutton.h"  @implementation Mybutton - (void) Addnewtarget: (ID) Target Action: (SEL) action{//The target action is saved to the property.     Self. Target= target; Self. Action= action;}//4. Give him a trigger condition.- (void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{[ Self. TargetPerformselector: Self. ActionWithobject: Self];}@end

Back to the root view of the. m file, the code is as follows:

#import "MainViewController.h" #import "Mybutton.h"  @interface mainviewcontroller ()@end @implementation mainviewcontroller - (void) Viewdidload {[SuperViewdidload];additional setup after loading the view.    //Use UIView to simulate a button's Click event.Mybutton *view_button = [[Mybutton alloc] Initwithframe:cgrectmake ( -, -, Max, -)]; View_button. BackgroundColor= [UicolorOrangecolor]; [ Self. ViewAddsubview:view_button]; [View_button release];//6. Using a custom method[View_button Addnewtarget: SelfAction:@selector(click:)];} - (void) Click: (Mybutton *) button{//detection is successful.    NSLog(@"Success!");}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

UI target...action design mode

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.