Target-Action模式

Target-Action 作用是解耦,通常用于单个事件,为了完成某一个任务,当某个事件发生时,调用那个对象中的方法
使用Target-Action实现一个颜色随机
内部实现: 在.h文件声明两个属性用于保存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];//颜色随机
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值