I have a UIToolbar
with a textfield which should move up when the keyboard is shown.
In my viewWillAppear
, I register my observer:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
(viewWillDisappear removes my observer)
And the function:
func keyboardWillShow(notification: NSNotification) {
println("will show")
let userInfo = notification.userInfo!
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue
let animations: () -> () = {
self.toolBar.frame.origin.y = self.view.frame.size.height - keyboardFrame.height - self.toolBar.frame.height
}
if animationDuration > 0 {
let options = UIViewAnimationOptions(UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).integerValue << 16)) // http://stackoverflow.com/a/18873820/242933
UIView.animateWithDuration(animationDuration, delay: 0, options: options, animations: animations, completion: nil)
} else {
animations()
}
}
Now when I tap the UITextField
, the keyboard comes up and calls keyboardWillShow
. But the animation does not happen until the keyboardWillShow
gets called a second time (having multiple keyboards does not work unless height changes; for example when the autocomplete bar changes state).
What am I doing wrong? Everywhere I look this is implemented in this way.
EDIT: More details:
animations() gets called with the correct height for the toolbar, but the UI doesn't put the toolbar in the correct place. Maybe it's something that's not yet initialized?
Even more details: When using the UIToolbar
as an inputAccessoryView
, when I tap the UITextField
, it doesn't come up above the keyboard, but when I start typing, it does. I am running out of options here...
Even more tries to find the problem: It seems that running any other animation works, like changing the height of the toolbar.