target/action 设计模式
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
RootViewController * rootVC = [[RootViewController alloc]init];
self.window.rootViewController = rootVC;
return YES;
}
RootViewController.m
@interface RootViewController ()
@property(nonatomic,strong)RootView * rv;
@end
@implementation RootViewController
-(void)loadView{
self.rv = [[RootView alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.view = _rv;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 添加点击事件
[self.rv.myButton myAddtarget:self action:@selector(myButtonAction:)];
}
-(void)myButtonAction:(MyButtonView *)sender{
NSLog(@"targetAction");
}
@end
RootView.h
#import <UIKit/UIKit.h>
#import "MyButtonView.h"
@interface RootView : UIView
@property(nonatomic,strong)MyButtonView * myButton;
@end
RootView.m
#import "RootView.h"
@implementation RootView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor yellowColor];
self.myButton = [[MyButtonView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
self.myButton.backgroundColor = [UIColor blueColor];
[self addSubview:_myButton];
}
return self;
}
@end
MyButtonView.h
#import <UIKit/UIKit.h>
@interface MyButtonView : UIView{
// 两个实例变量
// 谁执行方法
id _target;
// 执行什么方法
SEL _action;
}
// 方法:给两个实例变量赋值
-(void)myAddtarget:(id)target action:(SEL)action;
@end
MyButtonView.m
#import "MyButtonView.h"
@implementation MyButtonView
// 方法给两个实例变量赋值
-(void)myAddtarget:(id)target action:(SEL)action{
_target = target;
_action = action;
}
// 重写touchBegan
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[_target performSelector:_action withObject:self ];
}
@end