target-action设计模式
target-action是模仿系统的button。即将事件的处理交给外界,不在自己内部写死。
target-action设计模式主要涉及到两方面的内容
target:目标
action:动作
target-action可以让不同的实例对象在相同的时间点执行不同的方法,从而达到不同的效果
target-action设计模式存在的意义即将事件分离,View只负责显示,具体的事件处理交给controller。是MVC中View层和Controller层通信的一种方式。
#import <UIKit/UIKit.h> @interface TouchView : UIView #warning 1.给外界提供目标和动作属性,让外界可以设置。 @property(nonatomic, retain)id tagret; // 目标 @property(nonatomic, assign)SEL action; // 动作 @end
#import "TouchView.h" @implementation TouchView #warning 2.重写dealloc方法 释放对应的实例变量 - (void)dealloc { [_tagret release]; [super dealloc]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { #warning 4.在某个时间点让目标去执行对应的方法 [_tagret performSelector:_action withObject:self]; }
#import "RootViewController.h" #import "TouchView.h" @interface RootViewController () @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. TouchView *colorView = [[TouchView alloc] initWithFrame:CGRectMake(130, 50, 100, 100)]; colorView.backgroundColor = [UIColor redColor]; #warning 3.在外界设置target、action。 colorView.tagret = self; colorView.action = @selector(changeColor:); [self.view addSubview:colorView]; [colorView release]; TouchView *positionView = [[TouchView alloc] initWithFrame:CGRectMake(130, 250, 100, 100)]; positionView.backgroundColor = [UIColor greenColor]; positionView.tagret = self; positionView.action = @selector(changePosition:); [self.view addSubview:positionView]; [positionView release]; TouchView *sizeView = [[TouchView alloc] initWithFrame:CGRectMake(130, 450, 100, 100)]; sizeView.backgroundColor = [UIColor blueColor]; sizeView.tagret = self; sizeView.action = @selector(changeSize:); [self.view addSubview:sizeView]; [sizeView release]; } #warning 5.实现action方法,方法按需求实现 - (void)changeColor:(TouchView *)touchView { touchView.backgroundColor = [UIColor colorWithRed:(arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1]; } - (void)changePosition:(TouchView *)touchView { CGFloat minX = 0; CGFloat maxX = [[UIScreen mainScreen] bounds].size.width; CGFloat x = arc4random() % (int)(maxX - minX + 1) + minX; CGFloat minY = 0; CGFloat maxY = [[UIScreen mainScreen] bounds].size.height; CGFloat y = arc4random() % (int)(maxY - minY + 1) + minY; touchView.center = CGPointMake(x, y); } - (void)changeSize:(TouchView *)touchView { CGFloat minWidth = 38; CGFloat maxWidth = [[UIScreen mainScreen] bounds].size.width; CGFloat width = arc4random() % (int)(maxWidth - minWidth + 1) + minWidth; CGFloat minHeight = 38; CGFloat maxHeight = [[UIScreen mainScreen] bounds].size.height; CGFloat height = arc4random() % (int)(maxHeight - minHeight + 1) + minHeight; touchView.bounds = CGRectMake(0, 0, width, height); }