Skip to content

Instantly share code, notes, and snippets.

@theffc
Created November 7, 2021 20:50
Show Gist options
  • Save theffc/d32f93da210166b98b41015d7872d33c to your computer and use it in GitHub Desktop.
Save theffc/d32f93da210166b98b41015d7872d33c to your computer and use it in GitHub Desktop.
KeyboardSizeManager - Swift class to help adjust UI when the keyboard appears and disappears
import Foundation
import UIKit
final class KeyboardSizeManager {
private weak var bottomConstraint: NSLayoutConstraint?
private var oldValue: CGFloat
// MARK: - Init
public init(bottomConstraint: NSLayoutConstraint) {
self.bottomConstraint = bottomConstraint
oldValue = bottomConstraint.constant
addObservers()
}
deinit {
removeObservers()
}
private func addObservers() {
NotificationCenter.default.addObserver(
self,
selector: #selector(handleKeyboardChangeNotification(_:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(handleKeyboardWillHideNotification(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
private func removeObservers() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
// MARK: - Keyboard
@objc private func handleKeyboardChangeNotification(_ notification: Notification) {
let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
configureKeyboard(frame: keyboardFrame, notification: notification)
}
@objc private func handleKeyboardWillHideNotification(_ notification: Notification) {
configureKeyboard(frame: nil, notification: notification)
}
private func configureKeyboard(frame: CGRect?, notification: Notification) {
let curve = (notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue
let duration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
let options = UIView.AnimationOptions(rawValue: (curve ?? 0) << 16)
let keyboardFrame = frame ?? .zero
UIView.animate(
withDuration: duration ?? 0,
delay: 0,
options: options,
animations: {
guard let constraint = self.bottomConstraint else { return }
let isHiding = frame == nil
if isHiding {
constraint.constant = self.oldValue
} else {
constraint.constant = -keyboardFrame.height
}
},
completion: nil
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment