在所有程序员提高的方法中,几乎所有人都提到了要多读优秀的源码。所以在学习的路途中便开始了源码阅读的计划,至于从哪个源码开始呢,首先肯定是要自己经常用的,并且比较优秀的。所以最终确定为从MBProgressHUD开始进行源码计划。
功能
MBProgressHUD是一个为iOS添加悬浮层的框架,主要用在网络请求,弹窗提示等场景。
框架结构
MBProgressHUD包含了4个类,MBProgressHUD,MBRoundProgressView,MBBarProgressView,MBBackgroundView.
API结构
MBProgressHUD
方法
1 | + (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated; |
属性
1 | @property (weak, nonatomic) id<MBProgressHUDDelegate> delegate; |
MBRoundProgressView
1 | @property (nonatomic, assign) float progress; |
MBBarProgressView
1 | @property (nonatomic, assign) float progress; |
MBBackgroundView
1 | @property (nonatomic) MBProgressHUDBackgroundStyle style; |
调用流程
外部暴露的API主要分为show和hide两个类,不论是show还是hide,方法的最终调用都会走到animateIn:withType: completion:
,下面是方法调用流程图。
内部实现
show
1 | + (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated { |
hide
1 | + (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated { |
这里注意一下在拿当前hud时的方法.
1 | + (MBProgressHUD *)HUDForView:(UIView *)view { |
因为hud通常是最后放上去的,所以这里在拿hud的时候使用反向枚举器,可以减少循环次数。
而无论是show
方法,还是hide
方法,在设定animated属性为YES的前提下,最终都会走到animateIn: withType: completion:
方法:
1 | - (void)animateIn:(BOOL)animatingIn withType:(MBProgressHUDAnimation)type completion:(void(^)(BOOL finished))completion { |
收获
- 暴露出来的API最终都会走到同一个私有方法里。
- 使用CADisplayLink来刷新更新频率可能很高的view。
- 使用循环时,注意条件可以减少循环次数,进而对程序进行优化。
- 在添加hud时可以增加最小时间和延迟执行时间,避免一闪而过。