3

I have a view controller that makes a UITextField firstResponder on ViewWillAppear. Normally I could just rely on a UIKeyboardWillShow notification to detect if the keyboard has shown, but this won't trigger if I came into the current view controller while the keyboard was already showing.

Anyone have any ideas?

Vadoff
  • 9,219
  • 6
  • 43
  • 39

2 Answers2

8

I noticed while debugging view hierarchy that when keyboard is presented there's UIRemoteKeyboardWindow in hierarchy.

First we can add extension to UIApplication to check window hierarchy for UIRemoteKeyboardWindow:

extension UIApplication {
    var isKeyboardPresented: Bool {
        if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"), self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) {
            return true
        } else {
            return false
        }
    }
}

Then in viewDidLoad, or where needed we can check:

if UIApplication.shared.isKeyboardPresented {
   print("Keyboard is presented")
}

Although this method is not fully tested and UIRemoteKeyboardWindow is in private headers that's why NSClassFromString is needed for check. Use it with concern!

Najdan Tomić
  • 2,071
  • 16
  • 25
  • This works in many cases except when iOS email modal is invoked. Canceling the modal does returns keyboard presented true although it should be false – Markon Nov 06 '20 at 10:51
4

When you enter in a textField, it becomes first responder and then the keyboard will appears on your view. You can check the status of the keyboard in your viewWillAppear method [textField isFirstResponder]. If it returns YES, means your keyboard is visible.

-(void)viewWillAppear:(BOOL)animated{
     [super viewWillAppear:animated];
     if([textField isFirstResponder]){
       //visible keyboard
     }
}

Edited If you want the height than you can store the keyboard height in some class variable when it appears first time and use in viewWillAppear method

@implementation YourClass{
    CGFloat keyboardSize;
}

-(void)viewWillAppear:(BOOL)animated{
     [super viewWillAppear:animated];
     if([textField isFirstResponder]){
        //user keyboardSize here
     }
}
Vineet Choudhary
  • 7,433
  • 4
  • 45
  • 72
  • 1
    Not necessarily, if a hardware keyboard is used then the software keyboard will not be shown. Additionally, I'd like the actual notification to happen so that I could find the actual size of the keyboard on display. – Vadoff Sep 18 '15 at 05:03