新建一个MyButton类,继承于UIView.
![MyButton类](https://img-blog.csdn.net/20150917155744962)
MyButton.h
#import <UIKit/UIKit.h>
@interface MyButton : UIView
1.写一个自定义的方法.
- (void)addNewTarget:(id)target action:(SEL)action;
2.写两条属性,分别保存传过来的执行方法和委托人.
@property(nonatomic, assign)id target;
@property(nonatomic, assign)SEL action;
@end
MyButton.m
#import "MyButton.h"
@implementation MyButton
- (void)addNewTarget:(id)target action:(SEL)action {
3.通过属性保存传过来的委托者和需要执行的方法.
self.target = target;
self.action = action;
}
4.给MyView一个触发的方法.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
5.让MyView去调用执行委托人的方法.
[self.target performSelector:self.action withObject:self];
}
RootViewController.m
- (void)viewDidLoad {
MyButton *myButton = [[MyButton alloc]initWithFrame:CGRectMake(100, 200, 150, 50)];
myButton.layer.borderWidth = 1;
myButton.layer.cornerRadius = 10;
[self.view addSubview:myButton];
[myButton release];
6.对象去调用addNewTarget: action: 方法
[myButton addNewTarget:self action:@selector(test)];
}
- (void)test {
NSLog(@"***************");