iOS Target-Action

Target-Action是一种当一个事件发生时候,一个对象携带发送一个消息到另一个对象的必要的信息设计模式。存储的信息包括两类数据:标识所被调用的方法的动作选择器,和一个接收消息的目标。当被称作动作消息的事件发生的时候消息开始发送。尽管target可以是任何对象,甚至是框架对象,典型代表是以一种应用的特殊方式处理action message的一个自定义控制器。

    引发一个动作消息的事件可以是任何事物,比如对象发送消息可以为任何对象一样。举个例子:手势识别对象可能会发送一个动作消息给另一个对象当手势被识别的时候。然而target-action范例最普遍的发现在控制器例如按钮或者滑动条。当一个用户操作一个控制对象,它发送消息给特殊的对象。控制对象是UIControl的子类。action selecter和target object都是控制对象的属性。



target-Action 具体操作:

新建一个类继承于UIView

touchView.h


@interface TouchView : UIView


@property (assign, nonatomic) id target;

@property (assign, nonatomic) SEL action;


@end

touchView.m

#import "TouchView.h"


#import "MainViewController.h"

@implementation TouchView


- (void)dealloc{

    [super dealloc];

}

- (instancetype)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];

    if (self) {

        

    }

    return self;

}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{


}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{


}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    // target调用sel方法,并且传参数

//    [self.target performSelector:self.action withObject:self];

    // performSelector: 方法属于NSObject

    [(NSObject *)self.target performSelector:self.action withObject:self];

}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{


}


@end


mainViewController.m

#import "MainViewController.h"

#import "TouchView.h"

@interface MainViewController ()


@end


@implementation MainViewController


- (void)dealloc{

    [super dealloc];

}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        

    }

    return self;

}



- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    TouchView *aView = [[TouchView alloc] initWithFrame:CGRectMake(0, 50, 100, 100)];

    aView.target = self;

    aView.action = @selector(activeButton:);

    aView.backgroundColor = [UIColor blackColor];

    [self.view addSubview:aView];

    [aView release];


}


- (void)activeButton:(id)sender{

    NSLog(@"sender = %@", sender);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值