target - action设计模式的思想

不同的实例点击效果不同:点击改变自身颜色,点击改变父视图颜色,点击修改视图位置.以上效果可由target - action设计模式实现.
- (void)viewDidLoad
{
    [
super viewDidLoad];
    
// Do any additional setup after loading the view.
    
self.view.backgroundColor = [UIColor yellowColor];
    
CustomView *greenView = [[CustomView allocinitWithFrame:CGRectMake(2040280100)];
    greenView.
backgroundColor = [UIColor greenColor];
    [greenView 
addTarget:self acton:@selector(changeColor:) forControlEvents:UIControlEventTouchUpInside];
    [
self.view addSubview:greenView];
    [greenView 
release];
    
    
CustomView *redView = [[CustomView allocinitWithFrame:CGRectMake(20200280100)];
    redView.
backgroundColor = [UIColor redColor];
    [redView 
addTarget:self acton:@selector(changeSuperviewColor:) forControlEvents:UIControlEventTouchUpInside];
    [
self.view addSubview:redView];
    [redView 
release];
    
    
CustomView *blueView = [[CustomView allocinitWithFrame:CGRectMake(20360280100)];
    blueView.
backgroundColor = [UIColor blueColor];
    [blueView 
addTarget:self acton:@selector(changelocation:) forControlEvents:UIControlEventTouchUpInside];
    [
self.view addSubview:blueView];
    [blueView 
release];
}

- (
void)changeColor:(CustomView *)view
{
    view.
backgroundColor = [UIColor randomColor];
}

- (
void)changeSuperviewColor:(CustomView *)view
{
    view.
superview.backgroundColor = [UIColor randomColor];
}

- (
void)changelocation:(CustomView *)view
{
    view.
center = CGPointMake(arc4random() % 200 + 100arc4random() % 400 + 100);
}

@interface CustomView ()
{
    
id _target;    //目标
    
SEL _action;  //行为
    
UIControlEvents _controlEvents;
}
@end

// 为当前视图指定当视图接收到响应事件之后 , target 来通过 action 方法进行响应 .
- (
void )addTarget:( id )target acton:( SEL )action forControlEvents:( UIControlEvents )controlEvents
{
    
// 利用实例变量存储外界传入的参数 , 方便在其他方法中使用
    
_target  = target;
    
_action  = action;
    
_controlEvents  = controlEvents;
}

- (
void )touchesBegan:( NSSet  *)touches withEvent:( UIEvent  *)event
{
    
if  ( UIControlEventTouchDown  ==  _controlEvents ) {
        
// 当当前视图接收到触摸事件之后 , 交由 target 去处理
        [
_target   performSelector : _action   withObject : self ];
    }
 }   

- ( void )touchesEnded:( NSSet  *)touches withEvent:( UIEvent  *)event
{
    
if  ( UIControlEventTouchUpInside  ==  _controlEvents ) {
        [
_target   performSelector : _action   withObject : self ];
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值