How to add a UIView over the Keyboard - iOS

2019-04-02 14:09发布

问题:

I have been trying to display a toast message on iOS. What I did was when any notification comes, just I took the navigation controller view and added a subview for my toast message and displayed.

    UIView *top_view = self.navigationController.view;
    [top_view showToast:string];

Everything works fine. However my toast view is not adding over the keyboard(if the keyboard is at the front). Any idea what could be the problem... Little helps may save my time... Thanx..

回答1:

You can display the toast by adding subview to your main window.

UIWindow *toastDisplaywindow = [[[UIApplication sharedApplication] delegate] window];;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) 
{
   if (![[testWindow class] isEqual:[UIWindow class]]) 
    {
       self.toastDisplaywindow = testWindow;
       break;
    }
}
[toastDisplaywindow showToast:string];

If a keyboard is being displayed, it will be displayed as a separate window, above your usual main window. Hence a check made to find out if the keyboard is being displayed. If it is, then add the toast message on that window, else on the main window.

I found another method in this link, using which you can directly get to the UIView of the keyboard (If required).



回答2:

You have to add your subview to:

UIWindow *window = [UIApplication sharedApplication].windows.lastObject;

which is on top of the keyboard.



回答3:

Generally keyboard view is not part of your main window. it appears with new window when you get focused in any text field.

Try the following code to access your keyboard view.

[[[UIApplication sharedApplication] windows] objectAtIndex:1]

Remember, this will only work when you have keyboard on your screen.



回答4:

Another way is to add a custom UIWindow, then setting it's WindowLevel to +1 of the last window.

Something like this

NSArray *windows = [[UIApplication sharedApplication] windows];  
UIWindow *lastWindow = (UIWindow *)[windows lastObject];  
myWindow.windowLevel = lastWindow.windowLevel + 1;

Take a look to this topic https://forums.developer.apple.com/thread/16375



回答5:

Update for Swift3

UIApplication.shared.windows.last



回答6:

in iOS9 the answer by Adithya is not work,

UIWindow *window = [UIApplication sharedApplication].windows.lastObject;

work well