////MyButton.h//Ui04_target-action////Created by Dllo on 15/8/3.//Copyright (c) 2015 Zhozhicheng. All rights reserved.//#import <UIKit/UIKit.h> @interface MyButton : UIView //Achieve button click Effect via MyButton//1. Passing objects and actions to the inside of the class through a custom method-(void) AddTarget: (ID) Target action: (SEL) Action;//target: Target, Button executes the method of which class, the corresponding target is the object of that class//action: Action, let button specifically do what, the method of execution is the corresponding action//2. Save the corresponding target and action by two attributes@property(nonatomic,Assign)IDTarget@property(nonatomic,Assign) SEL Action;@end
////MYBUTTON.M//Ui04_target-action////Created by Dllo on 15/8/3.//Copyright (c) 2015 Zhozhicheng. All rights reserved.//#import "MyButton.h" @implementation MyButton -(void) AddTarget: (ID) Target Action: (SEL) action{//3. Implement the corresponding custom method, and have two properties to save the corresponding target and action Self. Action=action; Self. Target=target;}//4. Give the button a trigger condition, override the touch method, and just touch the Touchbegan method and let the button do the corresponding click Method-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//5. Class put his method to MyButton to complete.[ Self. TargetPerformselector: Self. ActionWithobject: Self];}@end
////MAINVIEWCONTROLLER.M//Ui04_target-action////Created by Dllo on 15/8/3.//Copyright (c) 2015 Zhozhicheng. All rights reserved.//#import "MainViewController.h" #import "MyButton.h" @interface mainviewcontroller ()@end @implementation mainviewcontroller - (void) Viewdidload {[SuperViewdidload];additional setup after loading the view. //through UIView to simulate a button clickMyButton *mybutton=[[mybutton Alloc] Initwithframe:cgrectmake ( -, -, Max, +)]; MyButton. BackgroundColor=[UicolorYellowcolor]; MyButton. Layer. BorderWidth=1; MyButton. Layer. Cornerradius=Ten; [ Self. ViewAddsubview:mybutton]; [MyButton release];//6. Using a custom method[MyButton AddTarget: SelfAction:@selector(click:)];} -(void) Click: (UIButton*) button{NSLog(@"Achieve Click Effect");} - (void) Didreceivememorywarning {[SuperDidreceivememorywarning];//Dispose of any resources, can be recreated.}/ * #pragma mark-navigation//in a storyboard-based application, you'll often want to do a little preparation before navigation-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) Sender {//Get the new view controller using [Segue Destinationviewcontroller]. Pass the selected object to the new view Controller.} */@end
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
IOS ui04_target-action