您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

SVProgressHUD 使用與源碼解讀:HUD 提示、通知與 Bundle 資源

編輯:iOS 技巧大全

SVProgressHUD 是項目裡常見的加載與提示組件,源碼本身也是一份不錯的實用 API 學習材料。本文從用法梳理到源碼裡值得借鑒的語言特性,做一次完整記錄。

倉庫地址:https://github.com/SVProgressHUD/SVProgressHUD

一、基本用法

它是單例,調用形如 [SVProgressHUD show...],可以寫在項目任意位置,但必須在主線程調用,否則會崩潰。展示時長由文本長度推算,區間約 0.5 至 5 秒。

// 常見展示方式
+ (void)showInfoWithStatus:(NSString *)string;
+ (void)showSuccessWithStatus:(NSString *)string;
+ (void)showErrorWithStatus:(NSString *)string;
+ (void)showImage:(UIImage *)image status:(NSString *)string;
+ (void)showProgress:(float)progress status:(NSString *)status;

// 關閉
+ (void)dismiss;
+ (void)dismissWithDelay:(NSTimeInterval)delay;
+ (void)dismissWithCompletion:(SVProgressHUDDismissCompletion)completion;
+ (void)dismissWithDelay:(NSTimeInterval)delay completion:(SVProgressHUDDismissCompletion)completion;

// 批量移除活動指示
+ (void)popActivity;

二、個性化定製

+ (void)setDefaultStyle:(SVProgressHUDStyle)style;             // 默認 SVProgressHUDStyleLight
+ (void)setDefaultMaskType:(SVProgressHUDMaskType)maskType;    // 默認 SVProgressHUDMaskTypeNone
+ (void)setDefaultAnimationType:(SVProgressHUDAnimationType)type; // 默認 SVProgressHUDAnimationTypeFlat
+ (void)setRingThickness:(CGFloat)width;                       // 默認 2 pt
+ (void)setCornerRadius:(CGFloat)cornerRadius;                 // 默認 14 pt
+ (void)setFont:(UIFont *)font;                                // 默認 Subheadline
+ (void)setForegroundColor:(UIColor *)color;                   // 僅 StyleCustom 有效
+ (void)setBackgroundColor:(UIColor *)color;                   // 僅 StyleCustom 有效
+ (void)setInfoImage:(UIImage *)image;
+ (void)setSuccessImage:(UIImage *)image;
+ (void)setErrorImage:(UIImage *)image;
+ (void)setViewForExtension:(UIView *)view;                    // 僅 App Extension 場景有效

圖標、文字樣式、背景色、圓角、遮罩都能調整,靈活度相當不錯。

三、四個生命週期通知

通過 NSNotificationCenter 註冊,可精確響應 HUD 的出現與消失:

SVProgressHUDWillAppearNotification —— 即將出現
SVProgressHUDDidAppearNotification —— 已經出現
SVProgressHUDWillDisappearNotification —— 即將消失
SVProgressHUDDidDisappearNotification —— 已經消失

每個通知的 userInfo 攜帶當前狀態字符串,可用 SVProgressHUDStatusUserInfoKey 取出。此外還會發送兩個觸摸相關通知:SVProgressHUDDidReceiveTouchEventNotification(用戶觸摸屏幕)與 SVProgressHUDDidTouchDownInsideNotification(直接觸摸 HUD),這兩個不帶 userInfo,但攜帶 UIEvent。

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDWillAppearNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDDidAppearNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDWillDisappearNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDDidDisappearNotification
                                               object:nil];
}

- (void)handleNotification:(NSNotification *)notification {
    NSLog(@"Notification recieved: %@", notification.name);
    NSLog(@"Status user info key: %@", notification.userInfo[SVProgressHUDStatusUserInfoKey]);
}
// 輸出示例:Status user info key: Useful Information

四、關鍵屬性枚舉

動畫類型 SVProgressHUDAnimationType

[SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];   // 圓圈轉動
[SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative]; // 系統菊花樣式

遮罩類型 SVProgressHUDMaskType

SVProgressHUDMaskTypeNone      // 顯示期間用戶仍可操作界面
SVProgressHUDMaskTypeClear     // 禁止操作
SVProgressHUDMaskTypeBlack     // 禁止操作,背景為黑色
SVProgressHUDMaskTypeGradient  // 禁止操作,背景為漸變

// 自定義遮罩色
[SVProgressHUD setBackgroundLayerColor:[[UIColor redColor] colorWithAlphaComponent:0.4]];
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];

樣式 SVProgressHUDStyle

[SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight]; // 白底黑字
[SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];  // 黑底白字
// 自定義配色需先設為 SVProgressHUDStyleCustom,再配置前景與背景色

五、源碼中的幾處巧思

顯示時長按文本長度推算,並設 0.5 秒下限,避免短提示一閃而過:

+ (NSTimeInterval)displayDurationForString:(NSString *)string {
    return MAX((float)string.length * 0.06 + 0.5, [self sharedView].minimumDismissTimeInterval);
}

讓某次調用使用臨時遮罩類型而不污染全局配置——先存全局值,展示後再還原:

+ (void)showSuccessWithStatus:(NSString *)status maskType:(SVProgressHUDMaskType)maskType {
    SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
    [self setDefaultMaskType:maskType];
    [self showSuccessWithStatus:status];
    [self setDefaultMaskType:existingMaskType];
}

通知中隨消息帶上提示文本,接收方可以直接取用:

[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidReceiveTouchEventNotification
                                                    object:self
                                                  userInfo:[self notificationUserInfo]];

- (NSDictionary *)notificationUserInfo {
    return (self.statusLabel.text ? @{SVProgressHUDStatusUserInfoKey : self.statusLabel.text} : nil);
}

六、值得學習的語言特性

__attribute__((deprecated)) 標記過時 API

+ (void)showWithMaskType:(SVProgressHUDMaskType)maskType
    __attribute__((deprecated("Use show and setDefaultMaskType: instead.")));

項目中一旦用到,編譯器會直接給出警告。

同族的 unavailable 用來禁止調用,例如不希望外部直接 init:

#define UNAVAILABLE_ATTRIBUTE __attribute__((unavailable))
#define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE

@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSUInteger age;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithName:(NSString *)name age:(NSUInteger)age;
@end

UI_APPEARANCE_SELECTOR 標記全局可配置屬性

@property (assign, nonatomic) SVProgressHUDStyle defaultStyle UI_APPEARANCE_SELECTOR;
@property (assign, nonatomic) SVProgressHUDMaskType defaultMaskType UI_APPEARANCE_SELECTOR;
@property (assign, nonatomic) SVProgressHUDAnimationType defaultAnimationType UI_APPEARANCE_SELECTOR;
@property (assign, nonatomic) CGSize minimumSize UI_APPEARANCE_SELECTOR;

加上這個標記後,才能通過 [SVProgressHUD appearance] 統一配置。

extern 修飾全局常量

頭文件裡用 extern 聲明、實現文件裡定義,常量會進入全局符號表,命名通常加上類名前綴避免衝突:

// SVProgressHUD.h
extern NSString * const SVProgressHUDDidReceiveTouchEventNotification;
extern NSString * const SVProgressHUDWillDisappearNotification;
extern NSString * const SVProgressHUDStatusUserInfoKey;

// SVProgressHUD.m
NSString * const SVProgressHUDDidReceiveTouchEventNotification = @"SVProgressHUDDidReceiveTouchEventNotification";
NSString * const SVProgressHUDWillDisappearNotification = @"SVProgressHUDWillDisappearNotification";
NSString * const SVProgressHUDStatusUserInfoKey = @"SVProgressHUDStatusUserInfoKey";

Bundle 資源包

Bundle 可以理解為資源文件包,把圖片、xib、文本組織在一起供多個項目引用。它是靜態的,不參與編譯,因此不能包含可執行文件,使用時需要通過路徑解析:

NSBundle *bundle = [NSBundle bundleForClass:[SVProgressHUD class]];
NSURL *url = [bundle URLForResource:@"SVProgressHUD" withExtension:@"bundle"];
NSBundle *imageBundle = [NSBundle bundleWithURL:url];
UIImage *infoImage    = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"info" ofType:@"png"]];
UIImage *successImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"success" ofType:@"png"]];
UIImage *errorImage   = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"error" ofType:@"png"]];

也可以定義宏簡化:

#define MYBUNDLE_NAME @"SVProgressHUD.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath:MYBUNDLE_PATH]

// 加載 bundle 內的 xib
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name" bundle:resourceBundle];

// 讀取 bundle 內的圖片
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIImage *image = [UIImage imageNamed:@"MyBundle.bundle/img_collect_success"];

UIView 的 tintColor

iOS 7 之後 UIView 新增了 tintColor,它定義了一個非默認著色值,會沿視圖層次向下傳播。默認值為 nil,表示沿用父視圖;若整個層次中都沒有非默認值,系統會使用藍色(RGB 約為 0、0.478、1)。想全局統一,設置 window 的 tintColor 即可。

UIImage 的 renderingMode

與 tintColor 配套,iOS 7 起 UIImage 提供了渲染模式:

UIImageRenderingModeAutomatic      // 根據使用環境自動調整(默認)
UIImageRenderingModeAlwaysOriginal // 始終繪製原始顏色
UIImageRenderingModeAlwaysTemplate // 始終使用 tintColor 渲染,忽略原圖顏色
UIImage *img = [UIImage imageNamed:@"myimage"];
img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

需要兼容舊系統時可先做能力檢測:

if ([[UIImage class] instancesRespondToSelector:@selector(imageWithRenderingMode:)]) {
    _infoImage    = [infoImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    _successImage = [successImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    _errorImage   = [errorImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
} else {
    _infoImage = infoImage; _successImage = successImage; _errorImage = errorImage;
}

UIControl 自定義控件

UIButton、UISlider、UIPageControl 等都繼承自 UIControl。它是抽象基類,不能被直接實例化,作用是把事件的分發邏輯統一收斂,讓子類專注於外觀與手勢跟蹤:

@interface ImageControl : UIControl
- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title image:(UIImage *)image;
@end
@implementation ImageControl {
    UILabel *_label;
    UIImageView *_imageView;
}

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title image:(UIImage *)image {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.layer.borderWidth = 1.0f;
        self.layer.borderColor = [UIColor grayColor].CGColor;
        self.layer.cornerRadius = 5.0f;
        self.layer.masksToBounds = YES;

        CGFloat width  = CGRectGetWidth(self.bounds);
        CGFloat height = CGRectGetHeight(self.bounds);

        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.image = image;
        [self addSubview:_imageView];

        _label = [[UILabel alloc] initWithFrame:(CGRect){0.0f, height - 30.0f, width, 30.0f}];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.textColor = [UIColor whiteColor];
        _label.text = title;
        [self addSubview:_label];
    }
    return self;
}

// 讓事件由控件自身處理
- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    [super sendAction:@selector(handleAction:) to:self forEvent:event];
}

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    [super beginTrackingWithTouch:touch withEvent:event];
    NSLog(@"Begin %d", self.tracking);
    return YES;
}

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    [super continueTrackingWithTouch:touch withEvent:event];
    NSLog(@"Continue %d %@", self.tracking, (self.touchInside ? @"YES" : @"NO"));
    return YES;
}

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    [super endTrackingWithTouch:touch withEvent:event];
    CGPoint position = [touch locationInView:self];
    // 只在文字區域放開才觸發
    if (CGRectContainsPoint(_label.frame, position)) {
        [self sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    NSLog(@"End %d", self.tracking);
}

- (void)cancelTrackingWithEvent:(UIEvent *)event {
    [super cancelTrackingWithEvent:event];
    NSLog(@"Cancel");
}

- (void)handleAction:(id)sender {
    NSLog(@"handle Action");
    NSLog(@"target-action: %@", self.allTargets);
}

@end

SVProgressHUD 用它做全屏遮罩,攔截 HUD 顯示期間的觸摸:

- (UIControl *)overlayView {
    if (!_overlayView) {
#if !defined(SV_APP_EXTENSIONS)
        CGRect windowBounds = [[[UIApplication sharedApplication] delegate] window].bounds;
        _overlayView = [[UIControl alloc] initWithFrame:windowBounds];
#else
        _overlayView = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
#endif
        _overlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _overlayView.backgroundColor = [UIColor clearColor];
        [_overlayView addTarget:self
                         action:@selector(overlayViewDidReceiveTouchEvent:forEvent:)
               forControlEvents:UIControlEventTouchDown];
    }
    return _overlayView;
}

小結

讀一個優秀的第三方庫,除了學會怎麼調用,更值得帶走的是它把「全局配置 + 單次覆蓋」「通知驅動生命週期」「資源包化」這些設計手法組織在一起的方式,以及對 deprecated、appearance、extern 這些語言特性的嫻熟運用。

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