Keyboard Sliding

A common problem in iOS development is the keyboard sliding up in front of a text view, blocking it from the user's view. There are a number of third-party libraries that handle this problem, but the core concept is to move the view up when keyboard appears, and slide it back down when the user is done.

To solve this problem, I need to remember the frame of the view prior to any keyboard interaction, and then use changes in the keyboard state to change the view frame.

class MyViewController: UIViewController {
    var loadedFrame: CGRect?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.prepareKeyboardHandling()

        // do other view stuff
    }
]

extension BaseCouponEditController {

    func prepareKeyboardHandling() {
        self.loadedFrame = self.view.frame

        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0 {
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        if self.view.frame.origin.y != 0 {
            self.view.frame = self.loadedFrame!
        }
    }
}

A simple reusable extension initialized in the viewDidLoad() method, and you're all set!