Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- final public class KeyboardObserving {
- public typealias ChangeSet = (keyboardRect: CGRect, animationCurve: UIView.AnimationOptions, duration: Double)
- public var onKeyboardWillShow: ((ChangeSet) -> Void)?
- public var onKeyboardWillHide: ((ChangeSet) -> Void)?
- public init() {
- registerKeyboardNotification()
- }
- deinit {
- removeKeyboardObservers()
- }
- public func removeKeyboardObservers() {
- NotificationCenter.default.removeObserver(self)
- }
- public func registerKeyboardNotification() {
- removeKeyboardObservers() // this should prevent from observing keyboard change twice.
- NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
- }
- // MARK: - Keyboard
- // MARK: will show
- @objc private func keyboardWillShow(_ notification: Notification) {
- guard
- let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
- let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
- let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
- else { return }
- onKeyboardWillShow?((keyboardRect, UIView.AnimationOptions(rawValue: curve.uintValue), duration.doubleValue))
- }
- // MARK: will hide
- @objc private func keyboardWillHide(_ notification: Notification) {
- guard
- let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
- let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
- let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
- else { return }
- onKeyboardWillShow?((keyboardRect, UIView.AnimationOptions(rawValue: curve.uintValue), duration.doubleValue))
- }
- }
- class ViewController: UIViewController {
- private let keyboardObserving = KeyboardObserving()
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view, typically from a nib.
- keyboardObserving.onKeyboardWillShow = { change in
- print("show", change)
- }
- keyboardObserving.onKeyboardWillHide = { change in
- print("hide", change)
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement