target/action 设计模式简单使用

Target-Action模式是ObjC里非常常见的对象之间方法调用的方式,不过ObjC把方法调用叫做Send Message.

一帮情况在和UI打交道时候处理各种GUI上的事件会利用到这种模式.相对应的.NET上的处理模式就是delegate/event. 不过,Target-ActionC语言所赐,更是灵活很多,编译期没有任何检查,都是运行时的绑定.

代码演示:

1.创建一个继承UIView的类

#import <UIKit/UIKit.h>

@interface TouchView : UIView
//模拟的Button的写法

//实现方法的独享
@property (nonatomic,assign) id target ;

//实现的方法
@property (nonatomic,assign) SEL action ;



@end

实现部分:

@implementation TouchView

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //self.target 实现self.action的方法
    //withObject:一般用来实现多线程之间的通信
    [self.target performSelector:self.action withObject:self];
    
    
}

@end

初始化:

#import "RootViewController.h"
#import "TouchView.h"
@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    // target / action
    /*
     面向对象编程的核心思想:高内聚,低耦合
     target/action:可以用来解耦
     */
    
    TouchView *touchView1 = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 175, 100)];
    touchView1.backgroundColor = [UIColor magentaColor];
    
    TouchView*touchView2 = [[TouchView alloc]initWithFrame:CGRectMake(100, 250, 175, 100)];
    touchView2.backgroundColor = [UIColor redColor];
    
    //对target赋值
    touchView1.target = self ;
    
    //指定要实现的方法,对action赋值
    touchView1.action = @selector(touchAction1:);
    touchView1.tag = 111 ;
    [self.view addSubview:touchView1];
    [touchView1 release];
    
    
    touchView2.target = self ;
    touchView2.action =@selector(touchAction2:) ;
    touchView2.tag = 222 ;
    [self.view addSubview:touchView2];
    [touchView2 release];
    
    
    
}

-(void) touchAction1:(TouchView *)touchView
{
    TouchView *tempTouchView = (TouchView *)[self.view viewWithTag:111];
    tempTouchView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:arc4random()%256/255.0];
}


-(void) touchAction2:(TouchView *)touchView{
    TouchView *tempTouchView1 = (TouchView *)[self.view viewWithTag:222];
//    tempTouchView1.center = CGPointMake(arc4random() %180 +90, arc4random() %567 + 50);
    tempTouchView1.frame = CGRectMake(arc4random() %201, arc4random() % 568, 175, 100);
    
}


@end


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值