Reputation: 9419
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?
Upvotes: 4
Views: 10184
Reputation: 2111
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!
Upvotes: 9
Reputation: 7633
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
}
}
Upvotes: 4