Move content for keyboard

The keyboard would cover my login form if I didn’t move the content upward. There are a number of ways to do this, but in this example I used my preferred method: adjust the view’s origin.




















Listen for the keyboard’s notifications:

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}


Remove the keyboard if the user taps in the view:

override func viewDidLoad() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
}


Adjust the view’s origin.

@objc func keyboardDidShow(notification: NSNotification) {
    var info = notification.userInfo
    let keyBoardSize = info![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
    view.frame.origin.y = -(keyBoardSize.height - (tabBarController?.tabBar.frame.height ?? 0.0))
}

@objc func keyboardDidHide(notification: NSNotification) {
    view.frame.origin.y = 0
}

Download Sample Project on GitHub