This is very simple to do and very common as well.
The idea of this example I'm going to pass is as follows, get the time the keyboard takes to go up or down and get the height it will occupy on the screen.
The first thing you need to do is to add a handler to the UIKeyboardWillChangeFrameNotification
event, which will notify you when the keyboard is rising or falling (you will notice that whether it goes up or down does not really matter) / p>
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onKeyboardChange(_:)), name:UIKeyboardWillChangeFrameNotification, object: nil);
And the onKeyboardChange
handler, which should be available in the self
scope, looks 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
}
Notice that when you apply height it will already vary the vertical position of the elements that you want to raise or lower in the UI, ie it does not matter if the keyboard is going up or down :)
And do not forget to remove the observer from the UIKeyboardWillChangeFrameNotification
event when you are no longer using it
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
That's it.