Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jul 25, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.