target/action设计模式
耦合
耦合是衡量一个程序写的好坏的标准之一,
耦合是衡量模块与模块之间关联程度的指标
“高内聚,低耦合”是面向对象编程的核心思想。
使用target…action实现解耦
例如:点击imageView实现换背景颜色 并且遵循MVC设计模式
1.准备工作:新建工程,新建一个视图控制器,将其设置为根视图控制器
2.新建一个ButtonView继承于UIView
3.在ButtonView.h中声明两个属性(记得dealloc)
@property (nonatomic, retain) id target;
@property (nonatomic, assign) SEL action;
4.重写初始化方法
- (instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action
{
self = [super initWithFrame:frame];
if (self) {
// 初始化时 对属性 进行赋值
self.target = target;
self.action = action;
}
return self;
}
5.添加触摸方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"开始触摸");
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"取消触摸");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"点击");
// 使用self.target对象调用 action方法
// 让一个对象 去调用这个对象类里的方法
// Object 可携带的参数
[self.target performSelector:self.action withObject:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
}
6.在根视图控制器的viewDidLoad中,创建ButtonView的对象
ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 200, 200) target:self action:@selector(buttonViewClick:)];
buttonView.backgroundColor = [UIColor redColor];
[self.view addSubview:buttonView];
[buttonView release];
7.实现方法
- (void)buttonViewClick:(ButtonView *)buttonView
{
// 改变背景颜色
butt