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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With