Skip to content

Instantly share code, notes, and snippets.

@cdzombak
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdzombak/0afedf56c34787b40d4c to your computer and use it in GitHub Desktop.
Save cdzombak/0afedf56c34787b40d4c to your computer and use it in GitHub Desktop.
iOS Keyboard Avoiding with Auto Layout
// in -loadView or similar…
self.completeButtonBottomConstraint = [NSLayoutConstraint constraintWithItem:self.completeButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-1.0*IDPCompleteButtonBottomSpacing];
// in -viewWillAppear:…
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWillShow:(NSNotification *)note {
[self updateBottomConstraintFromNotification:note];
}
- (void)keyboardWillHide:(NSNotification *)note {
[self updateBottomConstraintFromNotification:note];
}
- (void)updateBottomConstraintFromNotification:(NSNotification *)note {
NSDictionary *userInfo = note.userInfo;
CGFloat animationDuration = [as_option(userInfo[UIKeyboardAnimationDurationUserInfoKey], NSNumber) floatValue];
CGRect keyboardEndFrame = [as_option(userInfo[UIKeyboardFrameEndUserInfoKey], NSValue) CGRectValue];
CGRect convertedKeyboardEndFrame = [self.view convertRect:keyboardEndFrame fromView:self.view.window];
NSUInteger rawAnimationCurve = [as_option(userInfo[UIKeyboardAnimationCurveUserInfoKey], NSNumber) unsignedIntegerValue] << 16;
UIViewAnimationOptions animationOptions = (UIViewAnimationOptions)rawAnimationCurve;
self.completeButtonBottomConstraint.constant = -1.0f * (CGRectGetMaxY(self.view.bounds) - CGRectGetMinY(convertedKeyboardEndFrame) + IDPCompleteButtonBottomSpacing);
[UIView animateWithDuration:animationDuration delay:0.0 options:(UIViewAnimationOptions)UIViewAnimationOptionBeginFromCurrentState|animationOptions animations:^{
[self.view layoutIfNeeded];
} completion:nil];
}
@cdzombak
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment