Skip to content

Instantly share code, notes, and snippets.

@asciimike
Created October 2, 2015 16:40
Show Gist options
  • Save asciimike/9d30e0845fa77a878323 to your computer and use it in GitHub Desktop.
Save asciimike/9d30e0845fa77a878323 to your computer and use it in GitHub Desktop.
iOS Keyboard Helpers
-(void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShown:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark -
#pragma mark Keyboard show/hide notifications
- (void)keyboardShown:(NSNotification *)notification
{
CGSize keyboardSize = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
[UIView animateWithDuration:0.15f animations:^{
[self.view setFrame:CGRectMake(0, -keyboardSize.height, self.view.frame.size.width, self.view.frame.size.height)];
}];
}
-(void)keyboardHidden:(NSNotification *)notification
{
[UIView animateWithDuration:0.15f animations:^{
[self.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
}];
}
func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardShown:"), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardHidden:"), name:UIKeyboardDidHideNotification, object: nil)
}
func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidHideNotification, object: nil)
}
func keyboardShown(notification: NSNotification) {
var keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size
UIView.animateWithDuration(0.15, animations: {
self.view.frame.origin.y -= keyboardSize!.height
})
}
func keyboardHidden(notification: NSNotification) {
var keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size
UIView.animateWithDuration(0.15, animations: {
self.view.frame.origin.y += keyboardSize!.height
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment