Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Created November 1, 2016 14:13
Show Gist options
  • Save michaelevensen/944b3ef0cbc4ba8edeaf300f3de7eb20 to your computer and use it in GitHub Desktop.
Save michaelevensen/944b3ef0cbc4ba8edeaf300f3de7eb20 to your computer and use it in GitHub Desktop.
Adjust the view size based on whether the keyboard is open or closed. Sizes dynamically based on keyboard.
override func viewDidLoad() {
super.viewDidLoad()
// Listen for keyboard changes
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(sender: NSNotification) {
if let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
self.view.frame.origin.y -= keyboardHeight
}
}
func keyboardWillHide(sender: NSNotification) {
if let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
self.view.frame.origin.y += keyboardHeight
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment