Skip to content

Instantly share code, notes, and snippets.

@nazywamsiepawel
Created March 28, 2017 17:15
Show Gist options
  • Save nazywamsiepawel/ae79e0144d94f70b678b3b3968837fb4 to your computer and use it in GitHub Desktop.
Save nazywamsiepawel/ae79e0144d94f70b678b3b3968837fb4 to your computer and use it in GitHub Desktop.
handling keyboard Notifications with swift 3.swift
override function viewDidLoad() {
...
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
...
}
func keyboardWillShow(_ notification:Notification) {
adjustingHeight(true, notification: notification)
}
func keyboardWillHide(_ notification:Notification) {
adjustingHeight(false, notification: notification)
}
func keyboardWillChangeFrame(_ notification: Notification) {
adjustingHeight(false, notification: notification)
}
func adjustingHeight(_ show:Bool, notification:Notification) {
var userInfo = (notification as NSNotification).userInfo!
let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
let changeInHeight = (keyboardFrame.height ) * (show ? 1 : 0)
self.bottomSpace.constant = changeInHeight
UIView.animate(withDuration: animationDurarion, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
@peterkejun
Copy link

Great Example!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment