Skip to content

Instantly share code, notes, and snippets.

@astrokin
Created February 12, 2018 11:31
Show Gist options
  • Save astrokin/674c1eea0e7bb2d06efe2df5ff2b6e5c to your computer and use it in GitHub Desktop.
Save astrokin/674c1eea0e7bb2d06efe2df5ff2b6e5c to your computer and use it in GitHub Desktop.
Keyboard handling
//MARK: - Observers
extension UIViewController {
func addObserverForNotification(_ notificationName: Notification.Name, actionBlock: @escaping (Notification) -> Void) {
NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: OperationQueue.main, using: actionBlock)
}
func removeObserver(_ observer: AnyObject, notificationName: Notification.Name) {
NotificationCenter.default.removeObserver(observer, name: notificationName, object: nil)
}
}
//MARK: - Keyboard handling
extension UIViewController {
typealias KeyboardHeightClosure = (CGFloat) -> ()
func addKeyboardChangeFrameObserver(willShow willShowClosure: KeyboardHeightClosure?,
willHide willHideClosure: KeyboardHeightClosure?) {
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil, queue: OperationQueue.main, using: { [weak self](notification) in
if let userInfo = notification.userInfo,
let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let c = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt,
let kFrame = self?.view.convert(frame, from: nil),
let kBounds = self?.view.bounds {
let animationType = UIViewAnimationOptions(rawValue: c)
let kHeight = kFrame.size.height
UIView.animate(withDuration: duration, delay: 0, options: animationType, animations: {
if kBounds.intersects(kFrame) { // keyboard will be shown
willShowClosure?(kHeight)
} else { // keyboard will be hidden
willHideClosure?(kHeight)
}
}, completion: nil)
} else {
print("Invalid conditions for UIKeyboardWillChangeFrameNotification")
}
})
}
func removeKeyboardObserver() {
removeObserver(self, notificationName: NSNotification.Name.UIKeyboardWillChangeFrame)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment