iOS アプリがサーバーと通信している間ローディング表示を出すために、
MBProgressHUD を導入することにした。
MBProgressHUD の基本的な使い方。
まずサブビューに追加し、
self.hud = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:self.hud];
メッセージをセットして表示。
self.hud. labelText = @"Logding...";
[self.hud show:YES];
閉じるときは
[self.hide hide:YES];
で OK。
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
でも表示できるけど、中で勝手にサブビューに追加されるのが気に入らない。
ViewController 内で使いまわしたいので、メンバとして保持するようにしている。
MBProgressHUD が提供するのは、ローディング表示して閉じるだけ。
似た名前の SVProgressHUD みたいに、成功や失敗を表示する気の利いた機能は提供していない。
その代わりカスタムビューをセットできるから、自分で画像なり表示しろ、って感じだ。
SVProgressHUD っぽく使いたいので、自分は下記のようなカテゴリを作っている。
#import "MBProgressHUD.h"
@interface MBProgressHUD (Utils)
- (void)showWithStatus:(NSString*)string;
- (void)showSuccessWithStatus:(NSString*)string;
- (void)showErrorWithStatus:(NSString*)string;
@end
@implementation MBProgressHUD (Utils)
- (void)showWithStatus:(NSString *)string
{
self.labelText = string;
self.mode = MBProgressHUDModeIndeterminate;
[self show:YES];
}
- (void)showErrorWithStatus:(NSString *)string
{
FAKIcon *icon = [FAKIonIcons ios7CloseIconWithSize:28];
[icon addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor]];
UIImage *image = [icon imageWithSize:CGSizeMake(28, 28)];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
self.labelText = string;
self.mode = MBProgressHUDModeCustomView;
self.customView = imageView;
[self hide:YES afterDelay:2.0];
}
- (void)showSuccessWithStatus:(NSString *)string
{
FAKIcon *icon = [FAKIonIcons ios7CheckmarkIconWithSize:28];
[icon addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor]];
UIImage *image = [icon imageWithSize:CGSizeMake(28, 28)];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
self.labelText = string;
self.mode = MBProgressHUDModeCustomView;
self.customView = imageView;
[self hide:YES afterDelay:2.0];
}
@end
成功・失敗で表示するアイコンは FontAwesomeKit のものを使用。
使い方はこんな感じ。
[self.hud showWithStatus:@"Loading..."];
[self.hud showSuccessWithStatus:@"Success"];