IOS UI04_Target-Action
/// MyButton. h // UI04_Target-Action /// Created by dllo on 15/8/3. // Copyright (c) 2015 zhozhicheng. All rights reserved. // # import
@ Interface MyButton: UIView // click the button through MyButton // 1. upload the target and Action to the class's internal class through a custom method-(void) addTarget :( id) target action :( SEL) Action; // target: target, the method of the class that the button executes. The target is the object of the class. // action: action. The method that the button executes is the corresponding action. // 2. store the corresponding targets and actions through two attributes: @ property (nonatomic, assign) id target; @ 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 let the two attributes Save the Corresponding Target and Action self. action = action; self.tar get = target;} // 4. give the Button a trigger condition and override the touch method. When you touch the touchBegan method, the button will execute the corresponding click method-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {// 5. class to hand over his method to MyButton to complete export self.tar get into mselector: self. action withObject: 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 {[super viewDidLoad]; // Do any additional setup after loading the view. // simulate a Button through UIView and click MyButton * myButton = [[MyButton alloc] initWithFrame: CGRectMake (100,100,150, 40)]; myButton. backgroundColor = [UIColor yellowColor]; myButton. layer. borderWidth = 1; myButton. layer. cornerRadius = 10; [self. view addSubview: myButton]; [myButton release]; // 6. use the custom method [myButton addTarget: self Action: @ selector (click :)];}-(void) click :( UIButton *) button {NSLog (@ achieves click effect );} -(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} /* # pragma mark-Navigation // In a storyboard-based application, you will 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