您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

MBProgressHUD 源碼剖析:模式、佈局與顯示時機的設計細節

編輯:iOS 開發基礎

版本:0.9.1。MBProgressHUD 是 iOS 上常見的 HUD 元件,用於在執行背景任務時顯示 loading 視圖與最多兩段文字提示,最典型的場景就是等待網路回應。蘋果官方其實也有類似能力的 UIProgressHUD,但那是私有 API,如今已不能使用,因此社群普遍轉向這個實作。以下直接從源碼角度看它是怎麼做出來的。

模式設計

MBProgressHUD 以 MBProgressHUDMode 列舉描述外觀形態:

typedef enum {
    MBProgressHUDModeIndeterminate,          // 以 UIActivityIndicatorView 顯示,預設值
    MBProgressHUDModeDeterminate,            // 圓形餅圖進度
    MBProgressHUDModeDeterminateHorizontalBar, // 水平進度條
    MBProgressHUDModeAnnularDeterminate,     // 環形進度條
    MBProgressHUDModeCustomView,             // 自訂視圖,可顯示成功或失敗提示圖
    MBProgressHUDModeText                    // 只顯示文字
} MBProgressHUDMode;

透過切換 mode,你可以使用內建的進度視圖、換成自己的自訂視圖,或乾脆只顯示一段文字。

外觀組成

一個 MBProgressHUD 大致由四部分構成:

  1. loading 動畫視圖:由 mode 決定,可以是菊花、進度條,或自訂的 UIImageView。
  2. 標題文字(label):顯示主要提示,單行呈現,會依 labelText 自適應字級(有長度上限),過長時以「…」截斷。
  3. 詳情文字(detailsLabel):承載補充資訊,可多行;但必須在 labelText 有值且非空字串時才會顯示。
  4. 背景框:作為上述內容的襯底,讓 HUD 從畫面中凸顯出來。

對應的可自訂屬性包括:

@property (assign) float opacity;              // 背景框透明度,預設 0.8
@property (MB_STRONG) UIColor *color;          // 背景框顏色;設定後 opacity 失效
@property (assign) float cornerRadius;         // 圓角半徑,預設 10.0
@property (MB_STRONG) UIFont *labelFont;
@property (MB_STRONG) UIColor *labelColor;
@property (MB_STRONG) UIFont *detailsLabelFont;
@property (MB_STRONG) UIColor *detailsLabelColor;
@property (MB_STRONG) UIColor *activityIndicatorColor; // 菊花顏色,預設白色

還有一個有趣的屬性 dimBackground,會在 HUD 區域鋪上一層由中心向外擴散的漸層:

@property (assign) BOOL dimBackground;

其實作在 drawRect: 中,用 CGGradientCreateWithColorComponents 建立漸層,再以 CGContextDrawRadialGradient 由中心向外繪製。值得注意的是顏色值是寫死的,無法自訂,有興趣可以打開這個選項看實際效果。

建立、佈局與繪製

除了 initWithFrame:,它另外提供兩個初始化方法:

- (id)initWithWindow:(UIWindow *)window;
- (id)initWithView:(UIView *)view;

傳入的視圖僅作為 frame 的參照,並不會自動被加入;把 HUD 掛到畫面上仍需自行處理(也有便利類別方法可用,後述)。

控制佈局的屬性有:

@property (assign) float xOffset;   // 相對於父視圖中心的 x/y 偏移
@property (assign) float yOffset;
@property (assign) float margin;    // 各元素與 HUD 邊緣的間距
@property (assign) CGSize minSize;  // 背景框最小尺寸
@property (atomic, assign, readonly) CGSize size;
@property (assign, getter = isSquare) BOOL square; // 是否強制寬高相等

layoutSubviews 中有一段關鍵處理:HUD 會填滿整個父視圖,這也是它顯示時能屏蔽父視圖互動的原因。

- (void)layoutSubviews {
    [super layoutSubviews];
    // Entirely cover the parent view
    UIView *parent = self.superview;
    if (parent) {
        self.frame = parent.bounds;
    }
    // ...
}

佈局時會先依要顯示的視圖累加所需寬高,並對詳情文字設上限:

CGFloat remainingHeight = bounds.size.height - totalSize.height - kPadding - 4 * margin;
CGSize maxSize = CGSizeMake(maxWidth, remainingHeight);
CGSize detailsLabelSize = MB_MULTILINE_TEXTSIZE(detailsLabel.text, detailsLabel.font, maxSize, detailsLabel.lineBreakMode);
totalSize.width = MAX(totalSize.width, detailsLabelSize.width);
totalSize.height += detailsLabelSize.height;

接著由上而下依序擺放各視圖,最後算出 size 供背景框繪製使用。背景框本身在 drawRect: 中以 CGContextAddArc 拼出四個圓角後填滿,屬於最傳統的 Core Graphics 手繪寫法。

至於進度視圖的切換,則集中在 updateIndicators:水平進度條模式會換成 MBBarProgressView,餅圖與環形模式使用 MBRoundProgressView(環形時額外呼叫 setAnnular:),自訂模式套用 customView,文字模式則不顯示進度視圖。

顯示與隱藏

與顯示/隱藏相關的屬性設計得相當細緻:

@property (assign) MBProgressHUDAnimation animationType;
@property (assign) float minShowTime;      // 最短顯示時間,避免一閃而逝,預設 0
@property (assign) float graceTime;        // 寬限期:任務在這段時間內結束就不顯示 HUD
@property (assign) BOOL taskInProgress;    // 搭配 graceTime 使用的標記位
@property (assign) BOOL removeFromSuperViewOnHide;
@property (assign) float progress;         // 0.0 ~ 1.0
@property (copy) MBProgressHUDCompletionBlock completionBlock;

graceTime 與 taskInProgress 的搭配最值得一提。show: 的實作是:若 graceTime 大於 0,就建立計時器延後顯示;否則立即顯示。

- (void)show:(BOOL)animated {
    useAnimation = animated;
    if (self.graceTime > 0.0) {
        self.graceTimer = [NSTimer scheduledTimerWithTimeInterval:self.graceTime target:self
            selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
    } else {
        [self showUsingAnimation:useAnimation];
    }
}

- (void)handleGraceTimer:(NSTimer *)theTimer {
    // Show the HUD only if the task is still running
    if (taskInProgress) {
        [self showUsingAnimation:useAnimation];
    }
}

也就是說,只有當 taskInProgress 為 YES 時,寬限期結束後才真的顯示 HUD。若你打算自行呼叫 show:,務必記得設定這個標記。

另一組便利方法是「顯示 HUD 的同時跑背景任務」。以 target-action 形式的 showWhileExecuting:onTarget:withObject:animated: 為例:

- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated {
    methodForExecution = method;
    targetForExecution = MB_RETAIN(target);
    objectForExecution = MB_RETAIN(object);

    self.taskInProgress = YES;
    [NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil];
    [self show:animated];
}

launchExecution 中自帶 @autoreleasepool(因此呼叫端不必再包一層),任務結束後切回主執行緒執行 cleanUp 並隱藏 HUD。另一個基於 GCD 的版本 showAnimated:whileExecutingBlock:onQueue:completionBlock: 邏輯相同:先設 taskInProgress,把 block 丟到指定 queue,完成後回主執行緒清理。

隱藏的部分,hide:afterDelay: 建立在 hide: 之上,而 hide: 的重點是「最短顯示時間」的保障:

- (void)hide:(BOOL)animated {
    useAnimation = animated;
    if (self.minShowTime > 0.0 && showStarted) {
        NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:showStarted];
        if (interv < self.minShowTime) {
            self.minShowTimer = [NSTimer scheduledTimerWithTimeInterval:(self.minShowTime - interv)
                target:self selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO];
            return;
        }
    }
    [self hideUsingAnimation:useAnimation];
}

真正的收尾在私有方法 done 中:依 removeFromSuperViewOnHide 決定是否從父視圖移除、呼叫 completionBlock,最後觸發 delegate 的 hudWasHidden:。

其他細節

便利類別方法:

+ (MB_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated;
+ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated;
+ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated;

值得注意的是外觀屬性並沒有逐一生成 setter,而是改用 KVO 監聽。observableKeypaths 回傳一組 keyPath,registerForKVO 逐一註冊,observeValueForKeyPath 中若不在主執行緒則轉回主執行緒處理,最後由 updateUIForKeypath: 把值同步到對應的 label 或 indicator,並觸發 setNeedsLayout 與 setNeedsDisplay。

代理 MBProgressHUDDelegate 只定義了一個方法:

- (void)hudWasHidden:(MBProgressHUD *)hud;

不足之處

MBProgressHUD 的缺點是互動能力偏弱:代理只有一個 hudWasHidden:,也無法點擊 HUD 觸發操作。舉例來說,送出網路請求時顯示 HUD 很自然,但若使用者想在等待回應期間取消這次請求,元件本身並未提供對應的處理方式——這種時候只能自行改源碼。

與 SVProgressHUD 的差異

兩者思路相近,差別主要在實作細節:

  1. SVProgressHUD 對外一律是類別方法(顯示、隱藏、外觀設定),內部以單例承接;MBProgressHUD 則是標準的物件導向用法。
  2. SVProgressHUD 只有 loading 視圖、提示文字與背景框,沒有詳情文字。
  3. SVProgressHUD 預設提供成功、錯誤、資訊三種狀態視圖;MBProgressHUD 需靠 customView 自行實作。
  4. SVProgressHUD 提供點擊、顯示、隱藏等互動,但以 NSNotification 形式對外廣播,需要自行監聽。
  5. SVProgressHUD 部分 loading 動畫是以 Layer 動畫實作。

兩者各有取捨,可依專案需求與個人偏好選擇。

小結

整體而言,MBProgressHUD 的程式碼相當樸實:沒有晦澀的技巧,用到的都是常見 API,讀起來輕鬆;使用面也很友善,照著 GitHub 上的說明很快就能上手。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved