iOS开发 - TargetAction

来源:互联网 发布:淘宝定制耳机推荐 编辑:程序博客网 时间:2024/05/18 00:37

1.Demo描述:创建一个TouchView,继承自UIView,TouchView.h代码如下

@interface TouchView : UIView@property (nonatomic, assign)id target;@property (nonatomic, assign)SEL action;- (id)initWithTarget:(id)aTarget action:(SEL)action;@end
TouchView.m代码如下:

- (id)initWithTarget:(id)aTarget action:(SEL)action{    self = [super init];    if (self) {        _target = aTarget;        _action = action;    }    return  self;}//触摸开始- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [_target performSelector:_action withObject:self];}
然后在ViewController中我们这样写

TouchView * touchView = [[TouchView alloc]initWithTarget:self action:@selector(changeColor:)];    touchView.frame = CGRectMake(50, 50, 100, 100);    touchView.backgroundColor = [UIColor yellowColor];    [self.view addSubview:touchView];    [touchView release];

changeColor方法如下- (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];}


target - Action 设计模式好处

  • TouchView的作用只负责展示内容和响应用户的点击,但是当点击完toucheView,把要做的事情写到touchView类内部的话,无疑就是一个高耦合的状态,我们可以利用Target-Action设计模式,当targetView被点击的时候,touchView不作出任何处理,而是通知某对象执行某方法(让目标执行响应的动作),至于target要作出什么样的处理,跟视图没有关系了,就这样松开了耦合


1 0
原创粉丝点击