UIView 和 CALayer 有什么区别
UIView包含CALayer 的layer
UIView 对 CALayer 提供视图显示的内容 UIView 还对事件传递和响应链
这体现系统设计的 单一原则
事件传递机制:
事件传递和两个方法 有关
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;
屏幕点击时流程
点击屏幕 -> UIApplication -> UIWindow -> hittext:withEvent: -> pointInside: withEvent: -> Subvuews
当前视图(alpha > 0.01
ishidden == false isuserEnble = true )这些都成立
遍历是以倒序遍历调用 hitTest 方法 返回相应的视图
如果没有返回 nil
xcode 代码如下:
- (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 enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__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));
// 67.923
if (dis <= self.frame.size.width / 2) {
return YES;
}
else{
return NO;
}
}
事件响应流程:
苹果官网摘取:
屏幕快照 2018-11-14 上午11.37.38.png
事件响应的相关方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
留个例子:
假设如图
当c2接触到响应事件 他依次往上传递 当传递到A -> UIApplicationDelagate 之后 会发生什么??
网友评论