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

MBProgressHUD 原始碼分析與仿寫實作

編輯:iOS 開發基礎

前言

閱讀優秀的開源專案是提高開發人員技術水準的最佳方法之一,我們能從中開拓思維、拓寬視野,學習到許多設計思想與最佳實踐。若再動手仿寫、練習這些專案,能進一步加深理解,將這些知識內化為自己的能力。然而真正做起來卻很不容易,開源專案閱讀起來仍有一定難度,需要技術基礎與耐心。本系列將對一些著名的 iOS 開源類庫進行深入閱讀與分析,並練習仿寫其基本實現,以提升 iOS 開發的編程技能。

MBProgressHUD

MBProgressHUD 是一個 iOS 上的提示框庫,支援加載提示、進度框、文字提示等,使用簡單、功能強大,還能自定義顯示內容,廣泛應用於各類 iOS App。這是它的位址:https://github.com/jdg/MBProgressHUD

簡單看一下介面效果:

實現原理

MBProgressHUD 繼承自 UIView,實際上是一個覆蓋全屏的半透明指示器組件。它由以下幾部分構成:Loading 加載動畫、標題欄、背景欄以及其他欄(如詳情欄、按鈕)。我們把 MBProgressHUD 添加到頁面上,顯示任務進度與提示資訊,同時屏蔽使用者交互操作。

MBProgressHUD 的 Loading 加載動畫來自系統類 UIActivityIndicatorView,頁面加載時開啟轉圈動畫,銷毀時取消。它會根據加載內容動態布局,透過計算需要顯示的內容,動態調整頁面元素的位置大小,並置於螢幕中央,顯示內容可由使用者指定。v1.0 版之前透過 frame 計算各元素位置,最新版則採用約束布局。此外,它使用 KVO 監聽一些屬性值的變化(如 labelText、mode),這些屬性被修改時,視圖相應更新並傳入新值。

仿寫 MBProgressHUD

我們模仿 MBProgressHUD 寫一個簡單的彈出框組件,以加深理解。這個 demo 不完全重寫 MBProgressHUD,只實現基本功能。首先在 demo 中建立 ZCJHUD,繼承 UIView。

在 ZCJHUD 頭檔中,定義幾種顯示模式:

typedef NS_ENUM(NSInteger, ZCJHUDMode) {
    /** 轉圈動畫模式,預設值 */
    ZCJHUDModeIndeterminate,
    /** 只顯示標題 */
    ZCJHUDModeText
};

定義對外介面,顯示模式 mode 與標題內容 labelText:

@interface ZCJHUD : UIView
@property (nonatomic, assign) ZCJHUDMode mode;
@property (nonatomic, strong) NSString *labelText;
- (instancetype)initWithView:(UIView *)view;
- (void)show;
- (void)hide;
@end

自身初始化,設定組件預設屬性、更新布局、註冊 KVO 監視屬性變化:

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _mode = ZCJHUDModeIndeterminate;
        _labelText = nil;
        _size = CGSizeZero;
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
        self.alpha = 0;
        [self setupView];
        [self updateIndicators];
        [self registerForKVO];
    }
    return self;
}

初始化轉圈動畫並添加到 hud 上,僅 ZCJHUDModeIndeterminate 模式才有此動畫:

- (void)updateIndicators {
    BOOL isActivityIndicator = [_indicator isKindOfClass:[UIActivityIndicatorView class]];
    if (_mode == ZCJHUDModeIndeterminate) {
        if (!isActivityIndicator) {
            // 更新為 indeterminate 指示器
            [_indicator removeFromSuperview];
            self.indicator = ([[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]);
            [(UIActivityIndicatorView *)_indicator startAnimating];
            [self addSubview:_indicator];
        }
    } else if (_mode == ZCJHUDModeText) {
        [_indicator removeFromSuperview];
        self.indicator = nil;
    }
}

兩個主要方法——顯示與隱藏 hud:

-(void)show {
    self.alpha = 1;
}
-(void)hide {
    self.alpha = 0;
    [self removeFromSuperview];
}

這裡使用 frame 動態布局:

- (void)layoutSubviews {
    [super layoutSubviews];
    // 覆蓋整個視圖,屏蔽交互操作
    UIView *parent = self.superview;
    if (parent) {
        self.frame = parent.bounds;
    }
    CGRect bounds = self.bounds;
    CGFloat maxWidth = bounds.size.width - 4 * kMargin;
    CGSize totalSize = CGSizeZero;
    CGRect indicatorF = _indicator.bounds;
    indicatorF.size.width = MIN(indicatorF.size.width, maxWidth);
    totalSize.width = MAX(totalSize.width, indicatorF.size.width);
    totalSize.height += indicatorF.size.height;
    CGSize labelSize = MB_TEXTSIZE(_label.text, _label.font);
    labelSize.width = MIN(labelSize.width, maxWidth);
    totalSize.width = MAX(totalSize.width, labelSize.width);
    totalSize.height += labelSize.height;
    if (labelSize.height > 0.f && indicatorF.size.height > 0.f) {
        totalSize.height += kPadding;
    }
    totalSize.width += 2 * kMargin;
    totalSize.height += 2 * kMargin;
    // 定位元素
    CGFloat yPos = round(((bounds.size.height - totalSize.height) / 2)) + kMargin;
    CGFloat xPos = 0;
    indicatorF.origin.y = yPos;
    indicatorF.origin.x = round((bounds.size.width - indicatorF.size.width) / 2) + xPos;
    _indicator.frame = indicatorF;
    yPos += indicatorF.size.height;
    if (labelSize.height > 0.f && indicatorF.size.height > 0.f) {
        yPos += kPadding;
    }
    CGRect labelF;
    labelF.origin.y = yPos;
    labelF.origin.x = round((bounds.size.width - labelSize.width) / 2) + xPos;
    labelF.size = labelSize;
    _label.frame = labelF;
    _size = totalSize;
}

繪製背景框:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    CGContextSetGrayFillColor(context, 0.0f, 0.8);
    // 置中 HUD
    CGRect allRect = self.bounds;
    // 繪製圓角 HUD 背景矩形
    CGRect boxRect = CGRectMake(round((allRect.size.width - _size.width) / 2),
                                round((allRect.size.height - _size.height) / 2), _size.width, _size.height);
    float radius = 10;
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect));
    CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMinY(boxRect) + radius, radius, 3 * (float)M_PI / 2, 0, 0);
    CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMaxY(boxRect) - radius, radius, 0, (float)M_PI / 2, 0);
    CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMaxY(boxRect) - radius, radius, (float)M_PI / 2, (float)M_PI, 0);
    CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect) + radius, radius, (float)M_PI, 3 * (float)M_PI / 2, 0);
    CGContextClosePath(context);
    CGContextFillPath(context);
    UIGraphicsPopContext();
}

KVO 監控屬性變化,使用者修改屬性時觸發頁面刷新、賦上新值。注意頁面銷毀時要取消 KVO 監控,否則程式會崩潰:

#pragma mark - KVO
- (void)registerForKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
    }
}
- (void)unregisterFromKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [self removeObserver:self forKeyPath:keyPath];
    }
}
- (NSArray *)observableKeypaths {
    return [NSArray arrayWithObjects:@"mode", @"labelText", nil];
}
- (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"]) {
        [self updateIndicators];
    } else if ([keyPath isEqualToString:@"labelText"]) {
        _label.text = self.labelText;
    }
}
- (void)dealloc {
    [self unregisterFromKVO];
}

最終效果如下圖:

最後附上 demo 位址:https://github.com/superzcj/ZCJHUD

總結

MBProgressHUD 整體還算簡單,用到的都是些常見技術。希望透過這篇文章,動手仿寫一遍 MBProgressHUD,能更深刻地理解與認識它。

文章轉自 潇潇潇的簡

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