Target-Action 作用是解耦,通常用于单个事件,为了完成某一个任务,当某个事件发生时,调用那个对象中的方法
内部实现: 在.h文件声明两个属性用于保存Target和Action,
使用Target-Action实现一个颜色随机
我在这里定义了一个TargetActionPatterns类继承与UIView,和
#import <UIKit/UIKit.h>
@interface TargetActionPatterns : UIView
@property (nonatomic,assign)id target; //目标 ..注意类型
@property (nonatomic,assign)SEL action;//行动
- (void)addTarget:(id)target action:(SEL)action; //定义一个方法 方便外部调用
@end
在.m文件中
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[_target performSelector:_action withObject:self]; //执行选择器 一个事件制定一个对象
}
- (void)addTarget:(id)target action:(SEL)action
{
_target = target;
_action = action;
}
外部实现:在RootViewController类继承UIViewController
#import "RootViewController.h"
#import "TargetActionPatterns.h" //外部引用TargetActionPatterns.h头文件
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
TargetActionPatterns *view = [[TargetActionPatterns alloc]initWithFrame:CGRectMake(50, 50, 50, 50)];
view.backgroundColor = [UIColor redColor];
[view addTarget:self action:@selector(changeColor:)];
[self.view addSubview:view];
}
- (void)changeColor:(UIView *)view
{
view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];//颜色随机
}