This is very simple to do and common good too.
The idea of this example that I will pass is the following, get the time that the keyboard takes to climb or descend and get the height that it will occupy on the screen.
The first thing you need to do is add an Handler to the event UIKeyboardWillChangeFrameNotification
, that will notify you when the keyboard is going up or down (you will notice that knowing whether it goes up or down doesn’t matter much).
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onKeyboardChange(_:)), name:UIKeyboardWillChangeFrameNotification, object: nil);
And the Handler onKeyboardChange
, which must be available in scope self
gets like this:
func onKeyboardChange (notification: NSNotification )
{
let screenBounds = UIScreen.mainScreen().bounds
let info = notification.userInfo!
let keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
duration = info[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
let height = screenBounds.height - keyboardFrame.origin.y
// Daqui em diante, você pode animar suas views usando a duração
// e o height obtidos acima
}
Note that when you apply the height it will already vary the vertical position of the elements that you want to go up or down in the UI, that is, it doesn’t matter if the keyboard is going up or down :)
And don’t forget to remove Observer from the event UIKeyboardWillChangeFrameNotification
when no longer using it
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
That’s it.
Thank you very much, Rafael.
– Bruno Richart