小编给大家分享一下IOS开发之Target-Action模式有什么用,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
该模式主要是为了减少模块之间代码耦合性,以及增强模块内代码之间的内聚性.
让我们来看看一个实例:
1:假设有这么一个需求:我们点击一个视图对象,可以改变该视图的颜色,这个对于初学者来说是一件非常容易做到的事,只要在这个视图类中重写:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event函数,然后改变该视图的背景色即可,可是这时候又有了新的需求,一部分人需要在点击该视图改变该视图的颜色,一部分人需要在点击该视图时改变该视图的位置,为了让不同对象执行不同的事件,在实例化该视图类对象时需要指定该对象感兴趣的事件,对于这个需求我们可以通过定义枚举变量作为该对象的数据成员,并在初始化的时候指定枚举值(即指定感兴趣的事件),同时需要重写-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event函数,让它对不同的枚举值,执行不同的功能,假设这个时候我们又需要在点击该视图对象时,执行一个翻转功能,我们得又去修改该视图内的具体实现功能,这样代码之间的耦合性就比较大,移植起来就很不方便(试想这样的一个场景,假设别人的app需要你写好的这个视图类,但是别人不需要你视图类中事件方法,则需要修改该视图类,难免发生一些错误),解决这个问题的方法就是Target-Action模式,直接看代码:
//主视图头文件
#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController
@end
//主视图实现
#import "MainViewController.h"
#import "MyView.h"
@implementation MainViewController
-(id)init
{
self= [super init];
if (self)
{
}
return self;
}
-(void)viewDidLoad
{
MyView * view1 = [[MyView alloc]initWithFrame:CGRectMake(10, 20, 100, 100) andTarget:self andAction:@selector(changeColor:)];
[self.view addSubview:view1];
MyView * view2 = [[MyView alloc]initWithFrame:CGRectMake(10, 20, 100, 100) andTarget:self andAction:@selector(moveFrame:)];
[self.view addSubview:view2];
}
-(void)changeColor:(UIView *)aView
{
NSLog(@"buttonClick");
int red = arc4random()%255;
int green = arc4random()%255;
int blue = arc4random()%255;
aView.backgroundColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
}
-(void)moveFrame:(UIView *)aView
{
aView.frame = CGRectMake(arc4random()%320, arc4random()%480, 100, 100);
}
@end
//测试视图类头文件
#import <UIKit/UIKit.h>
@interface MyView : UIView
{
id _target;
SEL _action;
}
-(id)initWithFrame:(CGRect)frame andTarget:(id)target andAction:(SEL)action;
@property (assign,readwrite,nonatomic)id deledate;
@end
////测试视图类实现
#import "MyView.h"
@implementation MyView
-(id)initWithFrame:(CGRect)frame andTarget:(id)target andAction:(SEL)action
{
self = [super initWithFrame:frame];
if (self)
{
_target = target;
_action = action;
}
self.backgroundColor = [UIColor blueColor];
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_target performSelector:_action withObject:self];
}
@end
看完了这篇文章,相信你对“IOS开发之Target-Action模式有什么用”有了一定的了解,如果想了解更多相关知识,欢迎关注天达云行业资讯频道,感谢各位的阅读!