1.事件传递及相应
(1)UIView及CALayer
UIView为其提供内容,以及负责触摸等事件,参与视图事件相应链。
CALayer负责显示内容contents
(2)事件传递及视图相应链
a.事件传递
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
事件传递的流程
hitTest:withEvent:系统实现
代码实战
方形按钮指定区域接受事件相应
#import <UIKit/UIKit.h>
@interface CustomButton : UIButton
@end
#import "CustomButton.h"
@implementation CustomButton
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
if (!self.userInteractionEnabled || [self isHidden] || self.alpha <= 0.01) {
return nil;
}
if ([self pointInside:point withEvent:event]) {
//遍历当前对象的子视图
__block UIView *hit = nil;
[self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
CGPoint vonvertPoint = [self convertPoint:point toView:obj];
//调用子视图的hittest方法
hit = [obj hitTest:vonvertPoint withEvent:event];
//如果找到了接受事件的对象,则停止遍历
if (hit) {
*stop = YES;
}
}];
if (hit) {
return hit;
}else{
return self;
}
}else{
return nil;
}
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
CGFloat x1 = point.x;
CGFloat y1 = point.y;
CGFloat x2 = self.frame.size.width/2;
CGFloat y2 = self.frame.size.height/2;
double dis = sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2));
//以当前控件中心为圆心半径为当前控件宽度的圆内
if (dis <= self.frame.size.width/2) {
return YES;
}else{
return NO;
}
}
@end
b.事件相应
视图相应事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;