Skip to content

Instantly share code, notes, and snippets.

@chosa91
Last active May 18, 2018 13:54
Show Gist options
  • Save chosa91/6455b5ec679f404a4128e16479583c20 to your computer and use it in GitHub Desktop.
Save chosa91/6455b5ec679f404a4128e16479583c20 to your computer and use it in GitHub Desktop.
KeyboardSizedView
//
// Rewrited from Swift to obj-c
// Original source: https://github.com/objcio/app-architecture/blob/master/One-App-Eight-Architectures/MultiPattern/KeyboardSizedView.swift
//
@interface KeyboardSizedView ()
@property (nonatomic, strong) NSLayoutConstraint *keyboardConstraint;
@end
@implementation KeyboardSizedView
-(void)didMoveToSuperview
{
[super didMoveToSuperview];
if (self.superview == nil)
{
[NSNotificationCenter.defaultCenter removeObserver:self];
return;
}
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(keyboardChanged:)
name:UIKeyboardWillShowNotification
object:nil];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(keyboardChanged:)
name:UIKeyboardWillHideNotification
object:nil];
self.backgroundColor = UIColor.clearColor; // to be sure the backgroundColor isn't default(white)
}
#pragma mark - Notification handling
-(void)keyboardChanged:(NSNotification *)notification
{
NSDictionary *userInfo = notification.userInfo;
NSTimeInterval animationDuration = ((NSNumber *)userInfo[UIKeyboardAnimationDurationUserInfoKey]).doubleValue;
UIViewAnimationCurve animationCurve = ((NSNumber *)userInfo[UIKeyboardAnimationCurveUserInfoKey]).intValue;
CGRect rect = CGRectZero;
if (notification.name == UIKeyboardWillShowNotification)
{
rect = [self convertRect:((NSValue *)userInfo[UIKeyboardFrameEndUserInfoKey]).CGRectValue
fromView:nil];
rect.size.height -= (rect.origin.y + rect.size.height);
}
self.keyboardConstraint.constant = fmax(0., rect.size.height);
[UIView animateWithDuration:animationDuration
delay:0.
options:((animationCurve << 16) | UIViewAnimationOptionLayoutSubviews)
animations:^
{
[self layoutIfNeeded];
}
completion:nil];
}
#pragma mark - Lazy load
-(NSLayoutConstraint *)keyboardConstraint
{
if (_keyboardConstraint)
{
return _keyboardConstraint;
}
_keyboardConstraint = [self.heightAnchor constraintEqualToConstant:0.];
_keyboardConstraint.active = true;
return _keyboardConstraint;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment