您的位置:首页 > 移动开发 > IOS开发

iOS开发 - TargetAction

2015-11-16 14:38 459 查看
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要作出什么样的处理,跟视图没有关系了,就这样松开了耦合
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: