SVProgressHUD簡單使用以及自定義動畫

SVProgressHUD 是一個干凈,易于使用的HUD,旨在顯示iOS和tvOS正在進行的任務的進展。
常用的還有MBProgressHUD.這兩個都是很常用的HUD,大體相似,但是還是有一些不同的.
MBProgressHUD和SVProgressHUD的區別:
svprogresshud 使用起來很方便,但 可定制 差一些,看它的接口貌似只能添加一個全屏的HUD,不能把它添加到某個視圖上面去.
MBProgressHUD 功能全一些,可定制 高一些,而且可以指定加到某一個View上去.用起來可能就沒上面那個方便了.
具體還要看你的使用場景.
附上GitHub源碼地址:
SVProgressHUD:https://github.com/SVProgressHUD/SVProgressHUD
MBProgressHUD:https://github.com/jdg/MBProgressHUD
今天我們不對二者的區別做詳解,有空我會專門寫文章對它們的區別做一個詳解.
今天我們主要簡單介紹一下SVProgressHUD的使用.

安裝

通過CocoaPods安裝,在Podfile中加入pod 'SVProgressHUD',這里不多做介紹.可以參考文章: CocoaPods的簡單使用

使用

SVProgressHUD是已經被創建為單例的,所以不需要被實例化了,可以直接使用.調用它的方法[SVProgressHUD method].

[SVProgressHUD show ];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
     //耗時的任務
    dispatch_async(dispatch_get_main_queue(),^ {
        [SVProgressHUD dismiss ];
    });
});

顯示HUD

可以在下拉刷新或者執行其他耗時任務的時候,使用下面方法之一,來顯示不確定任務的狀態:

+ (void)show;
+ (void)showWithStatus:(NSString*)string;

效果圖分別為:


show(不帶文字)
showWithStatus(帶文字)

如果你希望HUD反應任務的進度,可以使用下面方法的其中一個:

+ (void)showProgress:(CGFloat)progress;
+ (void)showProgress:(CGFloat)progress status:(NSString*)status;

通過其他方式可以實現進度條的速度把控.比如:

- (IBAction)clickButtonsShowWithProgress:(id)sender {
    progress = 0.0f;
    [SVProgressHUD showProgress:0 status:@"Loading"];
    [self performSelector:@selector(increaseProgress) withObject:nil afterDelay:0.1f];
}

- (void)increaseProgress {
    progress += 0.05f;
    [SVProgressHUD showProgress:progress status:@"xuanhe Loading"];

    if(progress < 1.0f){
        [self performSelector:@selector(increaseProgress) withObject:nil afterDelay:0.1f];
    } else {
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:0.4f];
    }
}

效果如下


進度

還有其他常用的語法:

+(void)showInfoWithStatus :( NSString *)string;
+(void)showSuccessWithStatus :( NSString *)string;
+(void)showErrorWithStatus :( NSString *)string;
+(void)showImage:(UIImage *)image status :( NSString *)string;

取消HUD

HUD可以使用以下方式解除:

+(void)dismiss;
+(void)dismissWithDelay :( NSTimeInterval)delay;
+ (void)dismissWithDelay:(NSTimeInterval)delay completion:(SVProgressHUDDismissCompletion)completion;

可以對這些代碼進行改進,比如,在彈框結束后執行其他操作.可以封裝一個方法,彈框結束后,執行Block.

定制

SVProgressHUD 可以通過以下方法定制:

+ (void)setDefaultStyle:(SVProgressHUDStyle)style;                  // default is SVProgressHUDStyleLight
+ (void)setDefaultMaskType:(SVProgressHUDMaskType)maskType;         // default is SVProgressHUDMaskTypeNone
+ (void)setDefaultAnimationType:(SVProgressHUDAnimationType)type;   // default is SVProgressHUDAnimationTypeFlat
+ (void)setContainerView:(UIView*)containerView;                    // default is window level
+ (void)setMinimumSize:(CGSize)minimumSize;                         // default is CGSizeZero, can be used to avoid resizing
+ (void)setRingThickness:(CGFloat)width;                            // default is 2 pt
+ (void)setRingRadius:(CGFloat)radius;                              // default is 18 pt
+ (void)setRingNoTextRadius:(CGFloat)radius;                        // default is 24 pt
+ (void)setCornerRadius:(CGFloat)cornerRadius;                      // default is 14 pt
+ (void)setBorderColor:(nonnull UIColor*)color;                     // default is nil
+ (void)setBorderWidth:(CGFloat)width;                              // default is 0
+ (void)setFont:(UIFont*)font;                                      // default is [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline]
+ (void)setForegroundColor:(UIColor*)color;                         // default is [UIColor blackColor], only used for SVProgressHUDStyleCustom
+ (void)setBackgroundColor:(UIColor*)color;                         // default is [UIColor whiteColor], only used for SVProgressHUDStyleCustom
+ (void)setBackgroundLayerColor:(UIColor*)color;                    // default is [UIColor colorWithWhite:0 alpha:0.4], only used for SVProgressHUDMaskTypeCustom
+ (void)setImageViewSize:(CGSize)size;                              // default is 28x28 pt
+ (void)setInfoImage:(UIImage*)image;                               // default is the bundled info image provided by Freepik
+ (void)setSuccessImage:(UIImage*)image;                            // default is bundled success image from Freepik
+ (void)setErrorImage:(UIImage*)image;                              // default is bundled error image from Freepik
+ (void)setViewForExtension:(UIView*)view;                          // default is nil, only used if #define SV_APP_EXTENSIONS is set
+ (void)setGraceTimeInterval:(NSTimeInterval)interval;              // default is 0 seconds
+ (void)setMinimumDismissTimeInterval:(NSTimeInterval)interval;     // default is 5.0 seconds
+ (void)setMaximumDismissTimeInterval:(NSTimeInterval)interval;     // default is CGFLOAT_MAX
+ (void)setFadeInAnimationDuration:(NSTimeInterval)duration;        // default is 0.15 seconds
+ (void)setFadeOutAnimationDuration:(NSTimeInterval)duration;       // default is 0.15 seconds
+ (void)setMaxSupportedWindowLevel:(UIWindowLevel)windowLevel;      // default is UIWindowLevelNormal
+ (void)setHapticsEnabled:(BOOL)hapticsEnabled;                     // default is NO

樣式

作為標準SVProgressHUD提供兩種預先配置的樣式:

SVProgressHUDStyleLight白色背景黑色圖標和文字
SVProgressHUDStyleDark黑色背景與白色圖標和文本
如果要使用自定義顏色使用setForegroundColorsetBackgroundColor:。這些方法將HUD的風格置為SVProgressHUDStyleCustom

觸覺反饋

對于具有較新設備的用戶(從iPhone 7開始),SVProgressHUD可以根據顯示的HUD來自動觸發觸覺反饋。反饋圖如下:

  • showSuccessWithStatus: < - > UINotificationFeedbackTypeSuccess

  • showInfoWithStatus: < - > UINotificationFeedbackTypeWarning

  • showErrorWithStatus: < - > UINotificationFeedbackTypeError

要啟用此功能,請使用setHapticsEnabled:

具有iPhone 7之前的設備的用戶將不會改變功能。

通知

SVProgressHUD發布四個通知,NSNotificationCenter以響應被顯示/拒絕:

SVProgressHUDWillAppearNotification 提示框即將出現
SVProgressHUDDidAppearNotification 提示框已經出現
SVProgressHUDWillDisappearNotification 提示框即將消失
SVProgressHUDDidDisappearNotification 提示框已經消失

每個通知通過一個userInfo保存HUD狀態字符串(如果有的話)的字典,可以通過檢索SVProgressHUDStatusUserInfoKey

SVProgressHUD SVProgressHUDDidReceiveTouchEventNotification當用戶觸摸整個屏幕或SVProgressHUDDidTouchDownInsideNotification用戶直接觸摸HUD時也會發布。由于此通知userInfo未被傳遞,而對象參數包含UIEvent與觸摸相關的參數。

應用擴展

這里對這個功能不做詳解.自行摸索.

自定義動畫

SVProgressHUD提供了方法可以自定義圖片.但是不支持gif格式,直接利用下面的方法依然顯示一張靜態的圖片

[SVProgressHUD showImage:[UIImage imageNamed:@"loading.gif"] status:@"加載中..."];

我們可以把gif轉化為一個動態的image.
下面是我在百度上搜的一個方法.僅供參考.

#import <UIKit/UIKit.h>

typedef void (^GIFimageBlock)(UIImage *GIFImage);
@interface UIImage (GIFImage)

/** 根據本地GIF圖片名 獲得GIF image對象 */
+ (UIImage *)imageWithGIFNamed:(NSString *)name;

/** 根據一個GIF圖片的data數據 獲得GIF image對象 */
+ (UIImage *)imageWithGIFData:(NSData *)data;

/** 根據一個GIF圖片的URL 獲得GIF image對象 */
+ (void)imageWithGIFUrl:(NSString *)url and:(GIFimageBlock)gifImageBlock;

下面是.m的方法實現.

#import "UIImage+GIFImage.h"
#import <ImageIO/ImageIO.h>
@implementation UIImage (GIFImage)
+ (UIImage *)imageWithGIFData:(NSData *)data{
    
    if (!data) return nil;
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    size_t count = CGImageSourceGetCount(source);
    UIImage *animatedImage;
    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
    } else {
        NSMutableArray *images = [NSMutableArray array];
        NSTimeInterval duration = 0.0f;
        for (size_t i = 0; i < count; i++) {
            // 拿出了Gif的每一幀圖片
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); 
            //Learning... 設置動畫時長 算出每一幀顯示的時長(幀時長)
            NSTimeInterval frameDuration = [UIImage sd_frameDurationAtIndex:i source:source];
            duration += frameDuration;
            // 將每幀圖片添加到數組中
            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            // 釋放真圖片對象
            CFRelease(image);
        }
        // 設置動畫時長
        if (!duration) {
            duration = (1.0f / 10.0f) * count; 
        }
        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
    }
    
    // 釋放源Gif圖片
    CFRelease(source);
    return animatedImage;
}
+ (UIImage *)imageWithGIFNamed:(NSString *)name{
    NSUInteger scale = (NSUInteger)[UIScreen mainScreen].scale;
    return [self GIFName:name scale:scale];
}

+ (UIImage *)GIFName:(NSString *)name scale:(NSUInteger)scale{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@@%zdx", name, scale] ofType:@"gif"];  
    if (!imagePath) {
        (scale + 1 > 3) ? (scale -= 1) : (scale += 1);
        imagePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@@%zdx", name, scale] ofType:@"gif"];    
    }
    if (imagePath) {
        // 傳入圖片名(不包含@Nx)
        NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
        return [UIImage imageWithGIFData:imageData];
    } else {
        imagePath = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
        if (imagePath) { 
            // 傳入的圖片名已包含@Nx or 傳入圖片只有一張 不分@Nx
            NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
            return [UIImage imageWithGIFData:imageData];
        } else {
            // 不是一張GIF圖片(后綴不是gif)
            return [UIImage imageNamed:name];   
        }  
    }
}
+ (void)imageWithGIFUrl:(NSString *)url and:(GIFimageBlock)gifImageBlock{
    NSURL *GIFUrl = [NSURL URLWithString:url];
    if (!GIFUrl) return;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *CIFData = [NSData dataWithContentsOfURL:GIFUrl];
        // 刷新UI在主線程
        dispatch_async(dispatch_get_main_queue(), ^{
            gifImageBlock([UIImage imageWithGIFData:CIFData]);
        }); 
    });
}
#pragma mark - <關于GIF圖片幀時長(Learning...)>
+ (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float frameDuration = 0.1f;
    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTimeUnclampedProp) {
        frameDuration = [delayTimeUnclampedProp floatValue];
    } 
    else {
        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTimeProp) {
            frameDuration = [delayTimeProp floatValue];
        }
    }
    // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
    // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
    // a duration of <= 10 ms. See and
    // for more information.
    if (frameDuration < 0.011f) {
        frameDuration = 0.100f;
    }
    CFRelease(cfFrameProperties);
    return frameDuration;
}
@end

這個是UIimage的分類,在用到的控制器里面調用代碼方法即可.這個分類實現我也不太懂.只會用.

   _imgView1.image = [UIImage imageWithGIFNamed:@"xuanxuan"];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"xuanxuan" ofType:@"gif"];
    NSData *imgData = [NSData dataWithContentsOfFile:path];
    _imgView2.image = [UIImage imageWithGIFData:imgData];
    
    
    [UIImage imageWithGIFUrl:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1495708809771&di=da92fc5cf3bdd684711ab5124ee43183&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fw%253D580%2Fsign%3D91bd6cd2d42a60595210e1121835342d%2F212eb9389b504fc215d0301ee6dde71190ef6d1a.jpg" and:^(UIImage *GIFImage) {
        _imgView3.image = GIFImage;
    }];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容