Skip to content

Instantly share code, notes, and snippets.

@safareli
Last active December 3, 2018 03:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safareli/d9270e7faaad3f8d151c to your computer and use it in GitHub Desktop.
Save safareli/d9270e7faaad3f8d151c to your computer and use it in GitHub Desktop.
@interface KeyBoardSizeView : UIView
@property (nonatomic,weak) NSLayoutConstraint* heightConstraint;
@end
#import "KeyBoardSizeView.h"
@implementation KeyBoardSizeView
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if(self = [super initWithCoder:aDecoder]){
[self setUp];
}
return self;}
-(instancetype)initWithFrame:(CGRect)frame{
if(self = [super initWithFrame:frame]){
[self setUp];
}
return self;
}
-(instancetype)init{
if(self = [super init]){
[self setUp];
}
return self;
}
-(void)awakeFromNib{
if(self.heightConstraint) return;
for (NSLayoutConstraint* constraint in self.constraints) {
if(constraint.firstAttribute == NSLayoutAttributeHeight){
self.heightConstraint = constraint;
break;
}
}
[self checkHeightConstraint];
}
-(void)setUp{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardChangeFrame:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardChangeFrame:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardChangeFrame:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
// uncomment for non-ARC:
// [super dealloc];
}
-(void)checkHeightConstraint{
if (!self.heightConstraint) {
@throw [NSException exceptionWithName:@"KeyBoardSizeView Exception" reason:@"height constraint isn't set" userInfo:nil];
}
}
-(void)keyboardChangeFrame:(NSNotification*)notification{
if(!self.superview) return;
[self checkHeightConstraint];
CGRect keyboardEndFrame;
[[notification userInfo][UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
keyboardEndFrame = [self.superview convertRect:keyboardEndFrame toView:nil];
UIViewAnimationCurve curve =[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
self.heightConstraint.constant = CGRectGetHeight(CGRectIntersection(self.superview.frame, keyboardEndFrame));
[self setNeedsUpdateConstraints];
[self setNeedsLayout];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationCurve:curve];
[UIView setAnimationBeginsFromCurrentState:YES];
[self.superview layoutIfNeeded];
[UIView commitAnimations];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment