target/action 设计模式

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

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

首先我们创建一个继承UIView的类

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface TouchView : UIView
 4 //模拟的Button的写法
 5 
 6 //实现方法的独享
 7 @property (nonatomic,assign) id target ;
 8 
 9 //实现的方法
10 @property (nonatomic,assign) SEL action ;
11 
12 
13 @end
 1 #import "TouchView.h"
 2 
 3 @implementation TouchView
 4 
 5 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
 6     //self.target 实现self.action的方法
 7     //withObject:一般用来实现多线程之间的通信
 8     [self.target performSelector:self.action withObject:self];
 9     
10     
11 }
12 
13 @end
 1 #import "RootViewController.h"
 2 #import "TouchView.h"
 3 @interface RootViewController ()
 4 
 5 @end
 6 
 7 @implementation RootViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     // Do any additional setup after loading the view.
12     self.view.backgroundColor = [UIColor whiteColor];
13     
14     // target / action
15     /*
16      面向对象编程的核心思想:高内聚,低耦合
17      target/action:可以用来解耦
18      */
19     
20     TouchView *touchView1 = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 175, 100)];
21     touchView1.backgroundColor = [UIColor magentaColor];
22     
23     TouchView*touchView2 = [[TouchView alloc]initWithFrame:CGRectMake(100, 250, 175, 100)];
24     touchView2.backgroundColor = [UIColor redColor];
25     
26     //对target赋值
27     touchView1.target = self ;
28     
29     //指定要实现的方法,对action赋值
30     touchView1.action = @selector(touchAction1:);
31     touchView1.tag = 111 ;
32     [self.view addSubview:touchView1];
33     [touchView1 release];
34     
35     
36     touchView2.target = self ;
37     touchView2.action =@selector(touchAction2:) ;
38     touchView2.tag = 222 ;
39     [self.view addSubview:touchView2];
40     [touchView2 release];
41     
42     
43     
44 }
45 
46 -(void) touchAction1:(TouchView *)touchView
47 {
48     TouchView *tempTouchView = (TouchView *)[self.view viewWithTag:111];
49     tempTouchView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:arc4random()%256/255.0];
50 }
51 
52 
53 -(void) touchAction2:(TouchView *)touchView{
54     TouchView *tempTouchView1 = (TouchView *)[self.view viewWithTag:222];
55 //    tempTouchView1.center = CGPointMake(arc4random() %180 +90, arc4random() %567 + 50);
56     tempTouchView1.frame = CGRectMake(arc4random() %201, arc4random() % 568, 175, 100);
57     
58 }
59 
60 
61 @end

 

posted @ 2015-10-06 20:17  YX祥  阅读(459)  评论(0编辑  收藏  举报