iOS中 target/action 设计模式

耦合是衡量一个程序写的好坏的标准之一
“⾼内聚,低耦合”是面向对象编程的核心思想。
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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值