耦合是衡量一个程序写的好坏的标准之一
“⾼内聚,低耦合”是面向对象编程的核心思想。
target/action 设计模式
使用target…action 实现解耦 降低耦合度
内三:
.h文件
//1: 声明两个实例变量 分别为记录执行者(target),方法(action)
@interface TouchView : UIView
{
id _target; //方法执行者
SEL _action; // 方法
}
//2: 通过方法 addTarget: action获取外部的执行者和方法
//获取 外部的执行者 以及 执行方法
-(void)addTarget:(id)target action:(SEL)action;
.m文件
//3: 在某个时机,让执行者执行方法
-(void)addTarget:(id)target action:(SEL)action
{
//记录传入的执行者 和 执行方法
_target = target;
_action = action;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//让方法执行者 执行方法 self就是视图本身
[_target performSelector:_action withObject:self];
}
外三:
在控制器里面
1:创建视图touchView1 touchView2 touchView3
2:添加点击事件
[touchView1 addTarget:self action:@selector(changeColor:)];
[touchView2 addTarget:self action:@selector(changePosist:)];
[touchView3 addTarget:self action:@selector(changeSize:)];
3:实现各个的事件方法
-(void)changeColor:(TouchView *)touchVIEW
{
touchVIEW.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
}
-(void)changePosist:(TouchView *)touchVIEW
{
touchVIEW.center= CGPointMake(arc4random()%(325 - 100 +1)+100, arc4random()%(400-100+1)+100);
}
-(void)changeSize:(TouchView *)touchVIEW
{
touchVIEW.bounds = CGRectMake(0, 0, arc4random()%(275 - 100 +1)+100, arc4random()%(200-100+1)+100);
}
“⾼内聚,低耦合”是面向对象编程的核心思想。
target/action 设计模式
使用target…action 实现解耦 降低耦合度
内三:
.h文件
//1: 声明两个实例变量 分别为记录执行者(target),方法(action)
@interface TouchView : UIView
{
id _target; //方法执行者
SEL _action; // 方法
}
//2: 通过方法 addTarget: action获取外部的执行者和方法
//获取 外部的执行者 以及 执行方法
-(void)addTarget:(id)target action:(SEL)action;
.m文件
//3: 在某个时机,让执行者执行方法
-(void)addTarget:(id)target action:(SEL)action
{
//记录传入的执行者 和 执行方法
_target = target;
_action = action;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//让方法执行者 执行方法 self就是视图本身
[_target performSelector:_action withObject:self];
}
外三:
在控制器里面
1:创建视图touchView1 touchView2 touchView3
2:添加点击事件
[touchView1 addTarget:self action:@selector(changeColor:)];
[touchView2 addTarget:self action:@selector(changePosist:)];
[touchView3 addTarget:self action:@selector(changeSize:)];
3:实现各个的事件方法
-(void)changeColor:(TouchView *)touchVIEW
{
touchVIEW.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
}
-(void)changePosist:(TouchView *)touchVIEW
{
touchVIEW.center= CGPointMake(arc4random()%(325 - 100 +1)+100, arc4random()%(400-100+1)+100);
}
-(void)changeSize:(TouchView *)touchVIEW
{
touchVIEW.bounds = CGRectMake(0, 0, arc4random()%(275 - 100 +1)+100, arc4random()%(200-100+1)+100);
}