第十六篇、MBprogressHUD的使用和获取当前的控制器

 简介:

  在开发应用的时候,为了更好的增加用户的体验,常常在客户端向服务端请求数据的时候,在适当的地方加上非模态HUD,让用户可以可以知道当前的进度,稍作等待。

  

MBProgressHUD 第三方框架Github地址

#import "AppDelegate+HUD.h"
#import "MBProgressHUD.h"

@implementation AppDelegate (HUD)

// 获取当前处于activity状态的view controller (常用于收到异地登录,退出登录的弹窗)
- (UIViewController *)activityViewController { UIViewController* activityViewController = nil; UIWindow *window = [[UIApplication sharedApplication] keyWindow]; // 如果是模态控制器用这个方法获取 UIViewController *appRootVC = window.rootViewController; UIViewController *topVC = appRootVC; if (topVC.presentedViewController) { topVC = topVC.presentedViewController; return topVC; } if(window.windowLevel != UIWindowLevelNormal) { NSArray *windows = [[UIApplication sharedApplication] windows]; for(UIWindow *tmpWin in windows) { if(tmpWin.windowLevel == UIWindowLevelNormal) { window = tmpWin; break; } } } NSArray *viewsArray = [window subviews]; if([viewsArray count] > 0) { UIView *frontView = [viewsArray objectAtIndex:0]; id nextResponder = [frontView nextResponder]; if([nextResponder isKindOfClass:[UIViewController class]]) { activityViewController = nextResponder; } else { activityViewController = window.rootViewController; } } return activityViewController; } /** * 因为网络请求是在异步线程中执行,只有主线程才可以更新UI */ // 显示加载 - (void) showHUD:(NSString *)msg { dispatch_async(dispatch_get_main_queue(), ^{ if ([self.window viewWithTag:88888]) { [[self.window viewWithTag:88888] removeFromSuperview]; } MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.window]; HUD.tag = 88888; [self.window addSubview:HUD]; HUD.label.text = msg; HUD.contentColor = [UIColor blackColor]; HUD.label.textColor = [UIColor colorWithRed:254.0/255 green:71.0/255 blue:67.0/255 alpha:1]; [HUD setUserInteractionEnabled:NO]; // 设置成非模态显示 [HUD showAnimated:YES]; }); } // 移除 - (void) removeHUD { dispatch_async(dispatch_get_main_queue(), ^{ [[self.window viewWithTag:88888] hideAnimated:YES]; [[self.window viewWithTag:88888] removeFromSuperViewOnHide]; }); } // 显示信息 - (void) showMessage:(NSString *) msg { dispatch_async(dispatch_get_main_queue(), ^{ [[self.window viewWithTag:88888] hideAnimated:YES]; [[self.window viewWithTag:88888] removeFromSuperViewOnHide]; MBProgressHUD *HUDText = [MBProgressHUD showHUDAddedTo:self.window animated:YES]; // 设置只是显示文本 HUDText.tag = 88888; HUDText.mode = MBProgressHUDModeText; HUDText.label.text = msg; HUDText.margin = 10.0f; // CGPoint currentOffset = HUDText.offset; // currentOffset.y = -[UIScreen mainScreen].bounds.size.height / 2 + 80; // 设置Y的起始位置 // HUDText.offset = currentOffset; HUDText.removeFromSuperViewOnHide = YES; [HUDText setUserInteractionEnabled:NO]; [HUDText hideAnimated:YES afterDelay:2.8]; }); }

 

posted on 2016-08-29 15:24  久冬不雨  阅读(252)  评论(0编辑  收藏  举报