Dracula
Dracula

Reputation: 3090

Swift how to detect if keyboard is fully visible or fully hidden only (and not partially visible)

This question is related to the following questions: Detect when keyboard is fully visible and prevent keyboard appearance handling code from adding extra offset for hidden element

I was initially using notifications like NSNotification.Name.UIKeyboardDidShow, NSNotification.Name.UIKeyboardDidHide hoping they would be triggered only once, hence enabling me to set a bool that the keyboard is fully displayed or that it is hidden.

But what I have noticed is that all the events: UIKeyboardWillShow, UIKeyboardDidShow, UIKeyboardWillHide, UIKeyboardDidHide, UIKeyboardWillChangeFrame, UIKeyboardDidChangeFrame are designed to trigger multiple times as the keyboard appears or disappears.

There seems to be no way to check if a keyboard is completely visible and not partially visible. All the answers I looked at listened to these notifications and did calculations to avoid the views from being hidden by the keyboard. But I could not find any way to see if a keyboard is fully displayed (or fully hidden)

I even looked into KeyboardObserver which makes it easier to observe keyboard events, But since it's still based on the default notifications, it's KeyboardEventType.didShow and KeyboardEventType.didHide are triggered multiple times as keyboard appears and disappears.

There should be a better way to tell if a keyboard is fully visible or not visible!

Upvotes: 0

Views: 1313

Answers (1)

Shima Daryabari
Shima Daryabari

Reputation: 54

Here is an example of a property to check if the keyboard is available in the screen:

extension UIApplication {

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

}

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

Upvotes: 1

Related Questions