Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if keyboard is currently shown, if I transitioned from another view controller that was already showing the keyboard?

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?

like image 939
Vadoff Avatar asked Oct 18 '25 08:10

Vadoff


1 Answers

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!

like image 160
Najdan Tomić Avatar answered Oct 19 '25 20:10

Najdan Tomić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!