I have a signup form that is vertically centered.
I would like to animate its move up when the keyboard appears.
However my implementation of:
1- Removing Align center Y to: Superview
2- Hooking into the keyboard frame
3- Installing a constraint based on the keyboard frame
Makes a very static displacement with no animation.
@IBOutlet weak var centerVertically: NSLayoutConstraint!
@IBOutlet weak var bottomDistance: NSLayoutConstraint!
(...)
func keyboardWillShow(notification: NSNotification) {
var info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
bottomDistance.constant = keyboardFrame.size.height + 20
UIView.animateWithDuration(2.0) { () -> Void in
self.view.removeConstraint(self.centerVertically)
self.view.addConstraint(self.bottomDistance)
}
}
func keyboardWillHide(notification: NSNotification) {
UIView.animateWithDuration(2.0) { () -> Void in
self.view.removeConstraint(self.bottomDistance)
self.view.addConstraint(self.centerVertically)
}
}
How do I properly animate the transition ?
Couple things, first you can hook into the animation cycle of the keyboard moving so that your animation will animate at the same time/duration.
Secondly, instead of adding and removing your constraints (this will cause your view to snap in place without animating), update the constant value on the constraint inside the animation block. Here is a snippet I am using in Objective-C, swift version should be trivial.
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
UIViewAnimationCurve curve = [[note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
double duration = [[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[UIView setAnimationCurve:curve];
this.verticalConstraint.constant = 100.0f;
[this.view layoutIfNeeded];
}
completion:nil];
[UIView commitAnimations];
}];