UIView和CALayer和有什么關(guān)系
- UIview中有個屬性layer,是CALayer類型。
- CALayer包含要顯示的內(nèi)容contents和backgroundcolor,實際上UIView的backgroundcolor是重寫CALayer的backgroundcolor。
- CALayer的contents中是backing store實際上是bitmap類型的位圖,我們可以理解為顯示到屏幕上的都是位圖。
UIView和CALayer和有什么區(qū)別
- UIView為CALayer顯示提供基礎(chǔ),UIView負責(zé)處理觸摸等事件,參與事件響應(yīng)鏈。
- CALayer只是負責(zé)提供顯示的內(nèi)容contents
- 為什么如此設(shè)計?遵循單一職責(zé)設(shè)計模式
事件傳遞與視圖響應(yīng)鏈
// 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
// 判斷點擊的位置是否在當(dāng)前視圖的范圍內(nèi)
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;
- 事件傳遞流程

QQ20181110-230934@2x.png
- 點擊屏幕時首先將事件傳遞給UIApplication,UIApplication將事件傳遞給UIWindow
- UIWindow調(diào)用hitTest返回響應(yīng)視圖,先通過pointInside:判斷是否在UIWindow范圍內(nèi),如果在的話會通過倒序的方式遍歷UIWIndow的子視圖找出響應(yīng)視圖,最后添加的子視圖會最先調(diào)用hitTest方法,遞歸調(diào)用hitTest返回找到的視圖。
- 視圖響應(yīng)鏈

QQ20181110-231003@2x.png
視圖事件響應(yīng)方法
- (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,響應(yīng)觸摸方法
- UIView不處理觸摸事件則一層層往上傳遞直到UIWindow(視圖響應(yīng)鏈)
- 如果都不處理則忽略