Ios-target-action Design Pattern Understanding
The essence of Target-action's design pattern is that the event generated in host invokes the action method of target.
Below we use a uiview to implement the UIButton click event.
@interface custombutton:uiview-(void) Addcustombutton: (ID) Target andselector: (SEL) action; @end @implementation custombutton{ ID _target; SEL _action;} -(void) Addcustombutton: (ID) Target andselector: (SEL) action{ if (target==_target) { return; } _target = target; _action = action;} -(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event{}-(void) touchesended: (Nsset *) touches withevent: ( Uievent *) event{ if (_target) { if ([_target respondstoselector:_action]) { [_target performselector:_ Action withobject:self];}}
Use
-(void) viewdidload { [super viewdidload]; Additional setup after loading the view, typically from a nib. CustomButton *btn = [[CustomButton alloc]initwithframe:cgrectmake (0, +,--)]; Btn.backgroundcolor = [Uicolor redcolor]; [Btn addcustombutton:self andselector: @selector (hello:)]; [Self.view addsubview:btn]; } -(void) Hello: (id) sender{ NSLog (@ "Hello customer");}
Run results
2015-03-29 17:09:03.803 target_action[1863:89334] Hello Customer
Running Memory state:
Ios-target-action Design Pattern Understanding