
關注倉庫,及時獲得更新:iOS-Source-Code-Analyze
MBProgressHUD 是一個為 iOS 應用添加半透明浮層 HUD 的第三方框架。作為純 UI 層面的庫,它的實現並不複雜,但裡面有不少值得借鑒的工程技巧。
MBProgressHUD 是 UIView 的子類,提供了一系列創建 HUD 的方法,其中最常用的是這三個:
+ (MB_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated {
MBProgressHUD *hud = [[self alloc] initWithView:view];
hud.removeFromSuperViewOnHide = YES;
[view addSubview:hud];
[hud show:animated];
return MB_AUTORELEASE(hud);
}
它與配套的 + hideHUDForView:animated: 構成創建/隱藏 HUD 最簡單的一組接口。
- initWithView: 會轉調 - initWithFrame:,在那裡為屬性設置一系列默認值:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Set default values for properties
self.animationType = MBProgressHUDAnimationFade;
self.mode = MBProgressHUDModeIndeterminate;
...
// Make it invisible for now
self.alpha = 0.0f;
[self registerForKVO];
...
}
return self;
}
注意兩點:初始 alpha 為 0,所以 HUD 加進視圖後並不可見;以及初始化過程中調用了 - registerForKVO,後文會講它的作用。
- (void)show:(BOOL)animated {
NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread.");
useAnimation = animated;
// 若設置了 graceTime,則延後顯示
if (self.graceTime > 0.0) {
NSTimer *newGraceTimer = [NSTimer timerWithTimeInterval:self.graceTime
target:self
selector:@selector(handleGraceTimer:)
userInfo:nil
repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:newGraceTimer forMode:NSRunLoopCommonModes];
self.graceTimer = newGraceTimer;
} else {
[self showUsingAnimation:useAnimation];
}
}
UIView 的操作必須在主線程進行,所以先用 [NSThread isMainThread] 做斷言。graceTime 為 0 時直接顯示,否則通過一個一次性 Timer 延後,該 timer 的 selector 最終調用的仍是 - showUsingAnimation:。順帶一提,這裡把 timer 加到了 NSRunLoopCommonModes,避免用戶滑動界面時延遲顯示失效。
- (void)showUsingAnimation:(BOOL)animated {
// 取消之前調度的 hideDelayed: 請求
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self setNeedsDisplay];
if (animated && animationType == MBProgressHUDAnimationZoomIn) {
self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f));
} else if (animated && animationType == MBProgressHUDAnimationZoomOut) {
self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f));
}
self.showStarted = [NSDate date];
// Fade in
if (animated) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.30];
self.alpha = 1.0f;
if (animationType == MBProgressHUDAnimationZoomIn || animationType == MBProgressHUDAnimationZoomOut) {
self.transform = rotationTransform;
}
[UIView commitAnimations];
} else {
self.alpha = 1.0f;
}
}
核心職責只有一件:根據 animationType 為 HUD 的出現配上合適的動畫。
typedef NS_ENUM(NSInteger, MBProgressHUDAnimation) {
/** Opacity animation */
MBProgressHUDAnimationFade,
/** Opacity + scale animation */
MBProgressHUDAnimationZoom,
MBProgressHUDAnimationZoomOut = MBProgressHUDAnimationZoom,
MBProgressHUDAnimationZoomIn
};
方法開頭調用 - cancelPreviousPerformRequestsWithTarget: 移除掛在該 HUD 上的所有待執行 selector,避免同一方法被重複觸發;同時用 self.showStarted 記錄出現時刻,供後續的延遲隱藏邏輯判斷。
+ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated {
MBProgressHUD *hud = [self HUDForView:view];
if (hud != nil) {
hud.removeFromSuperViewOnHide = YES;
[hud hide:animated];
return YES;
}
return NO;
}
實現思路與 show 版本對稱:先取出該 view 最上層的 HUD 實例。
+ (MB_INSTANCETYPE)HUDForView:(UIView *)view {
NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator];
for (UIView *subview in subviewsEnum) {
if ([subview isKindOfClass:self]) {
return (MBProgressHUD *)subview;
}
}
return nil;
}
之後的 - hide: 與 - hideUsingAnimation: 沒有太多特別之處,倒是收尾的 - done 值得一看,它負責真正執行完成回調:
- (void)done {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
isFinished = YES;
self.alpha = 0.0f;
if (removeFromSuperViewOnHide) {
[self removeFromSuperview];
}
#if NS_BLOCKS_AVAILABLE
if (self.completionBlock) {
self.completionBlock();
self.completionBlock = NULL;
}
#endif
if ([delegate respondsToSelector:@selector(hudWasHidden:)]) {
[delegate performSelector:@selector(hudWasHidden:) withObject:self];
}
}
當 block 指定的隊列執行時顯示 HUD,並在 HUD 消失時調用 completion。MBProgressHUD 提供了幾個便利版本:
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block;
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block
completionBlock:(MBProgressHUDCompletionBlock)completion;
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block
onQueue:(dispatch_queue_t)queue;
完整版本會異步在指定 queue 上跑 block,結束後回主線程調用 - cleanUp:
- (void)showAnimated:(BOOL)animated
whileExecutingBlock:(dispatch_block_t)block
onQueue:(dispatch_queue_t)queue
completionBlock:(MBProgressHUDCompletionBlock)completion {
self.taskInProgress = YES;
self.completionBlock = completion;
dispatch_async(queue, ^(void) {
block();
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self cleanUp];
});
});
[self show:animated];
}
當後台任務在新線程中執行時顯示 HUD:
- (void)showWhileExecuting:(SEL)method
onTarget:(id)target
withObject:(id)object
animated:(BOOL)animated {
methodForExecution = method;
targetForExecution = MB_RETAIN(target);
objectForExecution = MB_RETAIN(object);
// Launch execution in new thread
self.taskInProgress = YES;
[NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil];
// Show HUD view
[self show:animated];
}
- (void)launchExecution {
@autoreleasepool {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
// Start executing the requested task
[targetForExecution performSelector:methodForExecution withObject:objectForExecution];
#pragma clang diagnostic pop
// 任務完成,回主線程更新視圖
[self performSelectorOnMainThread:@selector(cleanUp)
withObject:nil
waitUntilDone:NO];
}
}
- launchExecution 顯式包了一層 @autoreleasepool,避免子線程中臨時對象積壓;任務結束後切回主線程收尾,符合 UI 只能在主線程操作的約束。
用宏兼容 MRC 與 ARC
#ifndef MB_INSTANCETYPE
#if __has_feature(objc_instancetype)
#define MB_INSTANCETYPE instancetype
#else
#define MB_INSTANCETYPE id
#endif
#endif
#ifndef MB_STRONG
#if __has_feature(objc_arc)
#define MB_STRONG strong
#else
#define MB_STRONG retain
#endif
#endif
#ifndef MB_WEAK
#if __has_feature(objc_arc_weak)
#define MB_WEAK weak
#elif __has_feature(objc_arc)
#define MB_WEAK unsafe_unretained
#else
#define MB_WEAK assign
#endif
#endif
通過 __has_feature 判斷當前編譯環境是否啟用 ARC,讓同一份代碼在兩種內存管理模式下都能正確編譯。
用 KVO 代替一堆 setter
MBProgressHUD 通過 @property 暴露了一系列可配置項:
- (NSArray *)observableKeypaths {
return [NSArray arrayWithObjects:@"mode", @"customView", @"labelText", @"labelFont", @"labelColor",
@"detailsLabelText", @"detailsLabelFont", @"detailsLabelColor",
@"progress", @"activityIndicatorColor", nil];
}
如果為每個屬性都覆寫 setter 並在裡面刷新 UI,代碼會變得非常冗餘。這裡改用 KVO 統一處理:
- (void)registerForKVO {
for (NSString *keyPath in [self observableKeypaths]) {
[self addObserver:self
forKeyPath:keyPath
options:NSKeyValueObservingOptionNew
context:NULL];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(updateUIForKeypath:)
withObject:keyPath
waitUntilDone:NO];
} else {
[self updateUIForKeypath:keyPath];
}
}
- (void)updateUIForKeypath:(NSString *)keyPath {
if ([keyPath isEqualToString:@"mode"] || [keyPath isEqualToString:@"customView"] ||
[keyPath isEqualToString:@"activityIndicatorColor"]) {
[self updateIndicators];
} else if ([keyPath isEqualToString:@"labelText"]) {
label.text = self.labelText;
} else if ([keyPath isEqualToString:@"labelFont"]) {
label.font = self.labelFont;
} else if ([keyPath isEqualToString:@"labelColor"]) {
label.textColor = self.labelColor;
} else if ([keyPath isEqualToString:@"detailsLabelText"]) {
detailsLabel.text = self.detailsLabelText;
} else if ([keyPath isEqualToString:@"detailsLabelFont"]) {
detailsLabel.font = self.detailsLabelFont;
} else if ([keyPath isEqualToString:@"detailsLabelColor"]) {
detailsLabel.textColor = self.detailsLabelColor;
} else if ([keyPath isEqualToString:@"progress"]) {
if ([indicator respondsToSelector:@selector(setProgress:)]) {
[(id)indicator setValue:@(progress) forKey:@"progress"];
}
return;
}
[self setNeedsLayout];
[self setNeedsDisplay];
}
- observeValueForKeyPath:... 中的判斷是為了保證 UI 更新一定發生在主線程——KVO 回調可能來自任意線程,這一層保護很關鍵;實際刷新則交給 - updateUIForKeypath:。
作為一個 UI 庫,MBProgressHUD 的實現確實不複雜,但它在主線程斷言、RunLoop mode 選擇、MRC/ARC 兼容、KVO 批量屬性響應這幾處的處理,都值得在自己的項目中借鑒。