Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

Smooth transition for closing keyboard

I am working on a chat-app, and I was trying to have the user dismiss the keyboard interactively. Unfortunately, it is not working as I expected it to:

image

(This is with me beginning to pull the keyboard down. I would like my text view to stay on top of the keyboard no matter what. Here is what I have tried:

In viewDidLoad:

textView.keyboardDismissMode = .interactive//I have tried the same thing with the table view as well, but it produces the same result.

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

In the same class:

func keyboardWillShow(_ aNotification: NSNotification) {
    let info = aNotification.userInfo!
    let keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue()
    UIView.animate(withDuration: 0.25) { () -> Void in
        self.messageBottomConstraint.constant = keyboardFrame.height
        self.view.layoutIfNeeded()

    }
}

func keyboardWillHide(_ aNotification: NSNotification) {
    UIView.animate(withDuration: 0.25) { () -> Void in
        self.messageBottomConstraint.constant = 0
        self.view.layoutIfNeeded()

    }
}

How can I keep the text view at the top of the keyboard while the user is dismissing it? Thanks!

Upvotes: 0

Views: 336

Answers (1)

AdamPro13
AdamPro13

Reputation: 7400

You should be overriding the inputAccessoryView or inputAccessoryViewController property on UIResponder (which UIViewController inherits from). That will allow you to provide a view/view controller that automatically pins to the top of the keyboard when it appears.

This blog post gives an example of how to do this.

Upvotes: 1

Related Questions