13.target/action设计模式

来源:互联网 发布:如何利用网络学英语 编辑:程序博客网 时间:2024/06/05 02:52

使创建的自定义UIBttonView实现不同对象实现不同功能

1.首先创建一个继承于UIView的类

在ButtonView.h里

@interface ButtonView : UIView

2.添加属性一个是对象 一个自定义方法
@property (nonatomic,retain)id target;
@property (nonatomic,assign)SEL action;
自定义初始化方法
- (instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action;

在ButtonView.m里

-(void)dealloc
{
[_target release];
[super dealloc];
}

重写初始化方法
-(instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action
{
self = [super initWithFrame:frame];
if (self) {

    初始化时 对属性进行赋值    self.target = target;    self.action = action;}return self;

}

触摸开始触发
-(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
{

}

触摸中触发
- (void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event
{

}

触摸结束触发
- (void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event
{
NSLog(@”点击”);

让一个对象 去调用这个类里的方法Object 可携带的参数调用performSelector:withObject:方法使self.target对象调用 action方法[self.target performSelector:self.action withObject:self];

}

  • (void)touchesCancelled:(NSSet )touches withEvent:(UIEvent )event
    {

}
@end

在RootViewController.m文件中

RootViewController是根控制器
引入ButtonView.h头文件

-(void)viewDidLoad {
[super viewDidLoad];

// Do any additional setup after loading the view.

初始化一个ButtonView对象
ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 100, 100) target:self action:@selector(buttonViewClick:)];

buttonView.backgroundColor = [UIColor redColor];添加到根控制器视图上[self.view addSubview:buttonView];[buttonView release];

}

实现自定义按钮方法buttonViewClick
-(void)buttonViewClick:(ButtonView *)buttonView
{
buttonView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
}

0 0