import UIKit protocol KeyboardHandling: AnyObject { var scrollView: UIScrollView! { get set } var keyboardHandler: KeyboardHandler? { get set } } class KeyboardHandler { private weak var scrollView: UIScrollView? init(scrollView: UIScrollView) { self.scrollView = scrollView NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil ) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { scrollView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) } } @objc private func keyboardWillHide(notification: NSNotification) { scrollView?.contentInset = .zero } } class YourViewController: UIViewController { var scrollView: UIScrollView! var keyboardHandler: KeyboardHandler? override func viewDidLoad() { super.viewDidLoad() // Set up your scroll view // scrollView = ... // Call the KeyboardHandler to enable keyboard handling keyboardHandler = KeyboardHandler(scrollView: scrollView) } deinit { // Ensure to set keyboardHandler to nil when the view controller is deallocated keyboardHandler = nil } // Your other view controller code }