您的位置:首页 > 移动开发 > IOS开发

我的iOS学习历程 - TargetAction

2015-11-14 10:32 477 查看

什么是TargetAction?比如button继承于view,button可以通过添加点击事件来做出反应,但是view却不行,怎么让view也可以和button一样呢,这就是TargetAction的作用了:

首先我们自定义一个buttonView:

buttonView最重要的是需要两个属性:

1.action:需要实现的方法

2.target:谁来响应这个方法

所以我们需要重写初始化方法,把这两个属性添加进去(我们默认是关闭ARC以便于熟悉内存管理)

- (instancetype)initWithFrame:(CGRect)frame
target:(id)target
action:(SEL)action
{
self = [super initWithFrame:frame];
if (self) {
//  初始化时 对属性 进行赋值
self.action = action;
self.target = target;

}return self;
}


接下来就是写方法,要在点击结束是执行命令的话:(四个方法尽量写全)

重点:让某个对象调用某个方法用哪个参数用 performSelector这个方法

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

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

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//  使用self.target对象调用action方法
//  让一个对象去调用这个对象类里面的方法
//  Object 可携带的参数

[self.target performSelector:self.action withObject:self];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

}


这样我们一个具备button点击功能的view就好了,让我们来试试让这个view在点击后改变颜色:

1.先创建一个buttonView:

target填self就是自己来响应后面填的buttonViewClick这个方法

ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 100, 100) target:self action:@selector(buttonViewClick:)];


2.接下来写改变颜色的方法:

- (void)buttonViewClick:(ButtonView *)buttonView{
buttonView.backgroundColor = [UIColor colorWithRed:arc4random()%256 / 255.0 green:arc4random()%256 / 255.0 blue:arc4random()%256 / 255.0 alpha:1];
}


是不是很简单?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: