Skip to content

Instantly share code, notes, and snippets.

@dirkvranckaert
Last active September 7, 2017 09:04
Show Gist options
  • Save dirkvranckaert/9eb5b2f045d5cded8b4135c369977444 to your computer and use it in GitHub Desktop.
Save dirkvranckaert/9eb5b2f045d5cded8b4135c369977444 to your computer and use it in GitHub Desktop.
Keyboard and ScrollView behaviour example
@interface KeyboardAndScrollViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewBottomConstraint;
@end
@implementation KeyboardAndScrollViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"";
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardBecameVisible:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWentAway:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardBecameVisible:(NSNotification *)notification {
NSLog(@"Keyboard became visible");
// if we have no view or are not visible in any window, we don't care
if (!self.isViewLoaded || !self.view.window) {
return;
}
NSDictionary *userInfo = [notification userInfo];
CGRect keyboardFrameInWindow;
[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrameInWindow];
// the keyboard frame is specified in window-level coordinates. this calculates the frame as if it were a subview of our view, making it a sibling of the scroll view
CGRect keyboardFrameInView = [self.view convertRect:keyboardFrameInWindow fromView:nil];
float keyboardHeight = keyboardFrameInView.size.height;
NSLog([NSString stringWithFormat:@"KeyboardHeight=%f", keyboardHeight]);
[self.scrollView setNeedsUpdateConstraints];
[self.scrollViewBottomConstraint setConstant:keyboardHeight * -1.f];
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}
- (void)keyboardWentAway:(NSNotification *)notification {
NSLog(@"Keyboard went away");
// if we have no view or are not visible in any window, we don't care
if (!self.isViewLoaded || !self.view.window) {
return;
}
[self.scrollView setNeedsUpdateConstraints];
[self.scrollViewBottomConstraint setConstant:0];
[self.view setNeedsLayout];
[self.view 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