1

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.

vrwim
  • 13,020
  • 13
  • 63
  • 118

1 Answers1

0

I have found the answer in this GitHub repository which works for me

    let animations: () -> () = {
        if !(self.tableView.tracking || self.tableView.decelerating) {
            // Move content with keyboard
            if overflow > 0 {                   // scrollable before
                self.tableView.contentOffset.y += insetChange
                if self.tableView.contentOffset.y < -insetOld.top {
                    self.tableView.contentOffset.y = -insetOld.top
                }
            } else if insetChange > -overflow { // scrollable after
                self.tableView.contentOffset.y += insetChange + overflow
            }
        }
    }
vrwim
  • 13,020
  • 13
  • 63
  • 118