-
-
Save CavalcanteLeo/e1ff2d487804515af7e8 to your computer and use it in GitHub Desktop.
A great little helper for handling keyboard animations nicely. Just put this view at the bottom vertically of your views and it will move everything else up and down for you.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// YMKeyboardLayoutHelperView.m | |
// ios-chat | |
// | |
// Created by Steven Hepting on 7/17/13. | |
// Copyright (c) 2013 Yammer. All rights reserved. | |
// | |
#import "YMKeyboardLayoutHelperView.h" | |
#import "UIView+LayoutAdditions.h" | |
@interface YMKeyboardLayoutHelperView () | |
@property (nonatomic) CGFloat desiredHeight; | |
@property (nonatomic) CGFloat duration; | |
@end | |
@implementation YMKeyboardLayoutHelperView | |
- (id)init | |
{ | |
self = [super init]; | |
if (self) { | |
self.translatesAutoresizingMaskIntoConstraints = NO; | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; | |
} | |
return self; | |
} | |
- (void)keyboardWillShow:(NSNotification *)notification | |
{ | |
// Save the height of keyboard and animation duration | |
NSDictionary *userInfo = [notification userInfo]; | |
CGRect keyboardRect = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; | |
self.desiredHeight = CGRectGetHeight(keyboardRect); | |
self.duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; | |
[self animateSizeChange]; | |
} | |
- (void)keyboardWillHide:(NSNotification *)notification | |
{ | |
self.desiredHeight = 0.0f; | |
[self animateSizeChange]; | |
} | |
- (CGSize)intrinsicContentSize | |
{ | |
return CGSizeMake(UIViewNoIntrinsicMetric, self.desiredHeight); | |
} | |
- (void)animateSizeChange | |
{ | |
[self invalidateIntrinsicContentSize]; | |
// Animate transition | |
[UIView animateWithDuration:self.duration animations:^{ | |
[self.superview layoutIfNeeded]; | |
}]; | |
} | |
- (void)dealloc | |
{ | |
[[NSNotificationCenter defaultCenter] removeObserver:self]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment