target/Action设计模式
举例:点击view实现点击功能,改变背景颜色(类似button的addtarget方法)
创建ButtonView,遵守协议:
在ButtonView.h中:为了方便调用,声明成属性
@property (nonatomic, retain) id target;
@property (nonatomic, assign) SEL action;
// 初始化方法
- (instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action;
在ButtonView.m中:
- (void)dealloc
{
[self.target release];
[super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action
{
self = [super initWithFrame:frame];
if (self) {
// 初始化时,对属性进行赋值
self.target = target;
self.action = action;
}
return self;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// 使用self.target对象调用 action方法
// 让一个对象 去调用这个对象类里的方法
// Object 可携带的参数
[self.target performSelector:self.action withObject:self];
}
创建RootViewController作为根控制器
- (void)viewDidLoad {
[super viewDidLoad];
ButtonView *buttonView = [[ButtonView alloc]initWithFrame:CGRectMake(100, 100, 100, 100) target:self action:@selector(buttonClick:)];
buttonView.backgroundColor = [UIColor redColor];
[self.view addSubview:buttonView];
[buttonView release];
}
- (void)buttonClick:(ButtonView *)buttonView
{
buttonView.backgroundColor = [UIColor blackColor];