Button 可以将其分为展示和处理事件两部分,但其本身更加偏向于控制处理事件。展示层包括标题边框样式等等,控制处理事件用来进行交互,主要通过目标动作机制。
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"button" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(100, 100, 100, 100)];
Button 用来控制和用户进行交互的时候我们在使用时通过目标动作机制,也就是我们初始化好一个Button按钮后添加的这一个动作。
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
当用户在屏幕上进行点击时,如果是完整的实际上分为三个过程,touchesBegan,touchesMoved,touchesEnded三个过程。我们创建一个Button对象出来时,其内部封装了
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)even;
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
这三个系统方法。目标动作机制中我们给forControlEvents:输入的点击事件即(UIControlEventTouchUpInside,CustomEventTouchDrag,CustomEventTouchDown等),它来控制在action:这个参数中输入的函数(即回调函数)在touchesBegan,touchesMoved,touchesEnded那个过程中执行,即在哪个方法中触发action:中的回调函数。
在三个系统封装的方法中通过performSelector: withObject: 来实现对action:(即自己写的函数)的调用,判断和调用的形式如下
target,action,eventType为在使用目标动作机制时,我们输入的参数,当参数输入后,传入Button类创建的对象内部,进行赋值,
-(void)addTarget:(id)target action:(SEL)action event:(MyEventType)eventType{
// 将外部传递过来的参数保存为全局变量,使得其他方法中可以使用
self.target = target;
self.action = action;
self.eventType = eventType;
}
赋值后事件在Button创建的对象内部处理如下
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// 目标动作机制调用函数方法的方式
// selector:回调方法
// object:回调方法的参数
if (self.eventType == CustomEventTouchDown) {
[self.target performSelector:self.action withObject:self ];
};
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
if (self.eventType == CustomEventTouchDrag) {
[self.target performSelector:self.action withObject:self];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
if (self.eventType == CustomEventTouchUpInside) {
[self.target performSelector:self.action withObject:self];
}
}