"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