Last active
June 8, 2020 16:54
-
-
Save Revolucent/03fa833fc6ac9dbc52e50b8c675ec9d3 to your computer and use it in GitHub Desktop.
Modern implementation of KeyboardAvoidingViewController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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