Skip to content

Instantly share code, notes, and snippets.

@Revolucent
Last active June 8, 2020 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Revolucent/03fa833fc6ac9dbc52e50b8c675ec9d3 to your computer and use it in GitHub Desktop.
Save Revolucent/03fa833fc6ac9dbc52e50b8c675ec9d3 to your computer and use it in GitHub Desktop.
Modern implementation of KeyboardAvoidingViewController
import UIKit
open class KeyboardAvoidingViewController: UIViewController {
private var observers: [NSObjectProtocol] = []
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let nc = NotificationCenter.default
var observer = nc.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] note in
self?.animateSafeAreaInsetsForKeyboard(note.userInfo!)
}
observers.append(observer)
observer = nc.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] note in
self?.animateSafeAreaInsetsForKeyboard(note.userInfo!)
}
observers.append(observer)
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
observers.forEach(NotificationCenter.default.removeObserver)
observers = []
}
// MARK: Keyboard Observing
func animateSafeAreaInsetsForKeyboard(_ userInfo: [AnyHashable: Any]) {
//swiftlint:disable force_cast force_unwrapping
let keyboardFrameEnd = userInfo[UIResponder.keyboardFrameEndUserInfoKey]! as! CGRect
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey]! as! TimeInterval
let animationCurve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey]! as! Int
let animationOptions = UIView.AnimationOptions(rawValue: UInt(animationCurve << 16))
self.additionalSafeAreaInsets.bottom = keyboardFrameEnd.height - self.view.safeAreaInsets.bottom
UIView.animate(withDuration: animationDuration, delay: 0, options: animationOptions, animations: { [weak self] in
self?.view.layoutIfNeeded()
}, completion: nil)
//swiftlint:enable force_cast force_unwrapping
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment