UIView和CALayer和有什么关系
- UIview中有个属性layer,是CALayer类型。
- CALayer包含要显示的内容contents和backgroundcolor,实际上UIView的backgroundcolor是重写CALayer的backgroundcolor。
- CALayer的contents中是backing store实际上是bitmap类型的位图,我们可以理解为显示到屏幕上的都是位图。
UIView和CALayer和有什么区别
- UIView为CALayer显示提供基础,UIView负责处理触摸等事件,参与事件响应链。
- CALayer只是负责提供显示的内容contents
- 为什么如此设计?遵循单一职责设计模式
事件传递与视图响应链
// recursively calls -pointInside:withEvent:. point is in the receiver's coordinate system
// 判断点击的位置并返回被点击的view
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;
// default returns YES if point is in bounds
// 判断点击的位置是否在当前视图的范围内
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;
- 事件传递流程
QQ20181110-230934@2x.png
- 点击屏幕时首先将事件传递给UIApplication,UIApplication将事件传递给UIWindow
- UIWindow调用hitTest返回响应视图,先通过pointInside:判断是否在UIWindow范围内,如果在的话会通过倒序的方式遍历UIWIndow的子视图找出响应视图,最后添加的子视图会最先调用hitTest方法,递归调用hitTest返回找到的视图。
- 视图响应链
QQ20181110-231003@2x.png
视图事件响应方法
- (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;
- UIResponder的方法,UIView继承自UIResponder,响应触摸方法
- UIView不处理触摸事件则一层层往上传递直到UIWindow(视图响应链)
- 如果都不处理则忽略