Last active
April 11, 2016 09:29
-
-
Save jkmathew/dc753461af32c0c528655bb062847147 to your computer and use it in GitHub Desktop.
You have a textfield/textview in the bottom(like in message/whatsapp) of view and keyboard is hiding it? Don't worry, use the following code!!! Connect an NSLayoutConstraint via IBOutlet for the bottom spacing. Also, If you are not using presented view controller with modalPresentationStyle as UIModalPresentationFormSheet , no need to use UIKeyb…
This file contains hidden or 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
- (void)viewDidLoad { | |
//register for keyboard notification | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardDidShowNotification object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; | |
} | |
- (void)dealloc { | |
[[NSNotificationCenter defaultCenter] removeObserver:self]; | |
} | |
- (void)keyboardShow:(NSNotification *)notification { | |
CGRect keyboardFrameEnd = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; | |
CGFloat keyBoardAnimationDuration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]; | |
__weak typeof(self) weakSelf = self; | |
[UIView animateWithDuration:keyBoardAnimationDuration animations:^{ | |
weakSelf.messageContainerBottomSpace.constant = [weakSelf heightCoveredByKeyboardOfSize:keyboardFrameEnd]; | |
[weakSelf.view layoutIfNeeded]; | |
[weakSelf scrollToBottomAnimated:NO]; | |
}]; | |
} | |
- (void)keyboardWillHide:(NSNotification *)notification { | |
__weak typeof(self) weakSelf = self; | |
CGFloat keyBoardAnimationDuration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]; | |
[UIView animateWithDuration:keyBoardAnimationDuration animations:^{ | |
weakSelf.messageContainerBottomSpace.constant = 0; | |
[weakSelf.view layoutIfNeeded]; | |
}]; | |
} | |
- (CGFloat)heightCoveredByKeyboardOfSize:(CGRect)keyboardrect { | |
CGRect keyboardrectConverted = [self.view convertRect:keyboardrect fromView: nil]; | |
CGFloat bottomSpace = self.view.bounds.size.height - keyboardrectConverted.origin.y; | |
DLog("kframeConverted %@ bottomSpace %f self.view.bounds %@",NSStringFromCGRect(keyboardrectConverted),bottomSpace,NSStringFromCGRect(self.view.bounds)) | |
return bottomSpace; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment