Target-Action是一种当一个事件发生时候,一个对象携带发送一个消息到另一个对象的必要的信息设计模式。存储的信息包括两类数据:标识所被调用的方法的动作选择器,和一个接收消息的目标。当被称作动作消息的事件发生的时候消息开始发送。尽管target可以是任何对象,甚至是框架对象,典型代表是以一种应用的特殊方式处理action message的一个自定义控制器。
引发一个动作消息的事件可以是任何事物,比如对象发送消息可以为任何对象一样。举个例子:手势识别对象可能会发送一个动作消息给另一个对象当手势被识别的时候。然而target-action范例最普遍的发现在控制器例如按钮或者滑动条。当一个用户操作一个控制对象,它发送消息给特殊的对象。控制对象是UIControl的子类。action selecter和target object都是控制对象的属性。
target-Action 具体操作:
新建一个类继承于UIView
touchView.h
@interface TouchView : UIView
@property (assign, nonatomic) id target;
@property (assign, nonatomic) SEL action;
@end
touchView.m
#import "TouchView.h"
#import "MainViewController.h"
@implementation TouchView
- (void)dealloc{
[super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
// target调用sel方法,并且传参数
// [self.target performSelector:self.action withObject:self];
// performSelector: 方法属于NSObject
[(NSObject *)self.target performSelector:self.action withObject:self];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
}
@end
#import "MainViewController.h"
#import "TouchView.h"
@interface MainViewController ()
@end
@implementation MainViewController
- (void)dealloc{
[super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
TouchView *aView = [[TouchView alloc] initWithFrame:CGRectMake(0, 50, 100, 100)];
aView.target = self;
aView.action = @selector(activeButton:);
aView.backgroundColor = [UIColor blackColor];
[self.view addSubview:aView];
[aView release];
}
- (void)activeButton:(id)sender{
NSLog(@"sender = %@", sender);
}