12

When I try to show a MBProgressHUD while the keyboard is also showing, I use the code below but the HUD object cannot cover the keyboard:

SNSSharerAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
HUD = [[MBProgressHUD showHUDAddedTo:delegate.window animated:YES] retain];
HUD.mode = MBProgressHUDModeIndeterminate;
HUD.labelText = @"Posting...";
[HUD show:YES];

I thought the HUD object shows in front of the window of delegate, the keyboard shows too, so which added last, which is front. Am I wrong?

Smeegol
  • 2,014
  • 4
  • 29
  • 44

2 Answers2

17

Add hud to the second window which contains the keyboard. When keyboard showing, there are two UIWindow instances in application. The first one is the regular window, the second one is the temp keyboard window. Code:

UIWindow *tempKeyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
MBProgressHUD *hud=[[MBProgressHUD alloc] initWithWindow:tempKeyboardWindow];
hub.mode=MBProgressHUDModeIndeterminate;
hub.labelText=@"Sending...";
[tempKeyboardWindow addSubview:hud];
[hud show:YES];

Tested in ios4.3 and ios5.x, it really works.

OpenThread
  • 2,096
  • 3
  • 28
  • 49
  • +1, works on iOS7 too! To simplify the code just replace hud init method with this one: MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:tempKeyboardWindow animated:YES]; then you can delete the last two lines of code ([tempKeyboardWindow addSubview:hud]; and [hud show:YES];) – budiDino Mar 21 '14 at 08:45
  • application Crash for your Code. I am worked on ios12.2 – Bhumesh Purohit May 01 '19 at 10:33
2

for ios 9 instead [[[UIApplication sharedApplication] windows] objectAtIndex:1] try use [[[UIApplication sharedApplication] windows] lastObject]

so it will be like this

UIWindow *tempKeyboardWindow = [[[UIApplication sharedApplication] windows] lastObject];
MBProgressHUD *hud=[[MBProgressHUD alloc] initWithWindow:tempKeyboardWindow];
hub.mode=MBProgressHUDModeIndeterminate;
hub.labelText=@"Sending...";
[tempKeyboardWindow addSubview:hud];
[hud show:YES];
Roman
  • 366
  • 5
  • 19