adjust the textview when the keyboard will show in swift

To adjust the position of the UITextView when the keyboard will show in Swift, you can follow these steps:

  1. Add notification observers for UIKeyboardWillShowNotification and UIKeyboardWillHideNotification in your view controller’s viewDidLoad() method.
main.swift
override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
385 chars
7 lines
  1. In the observer method keyboardWillShow(notification:), retrieve the keyboard height and adjust the bottom constraint of your UITextView.
main.swift
@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        textViewBottomConstraint.constant = keyboardHeight + 16 // 16 is the padding
    }
}
321 chars
7 lines
  1. In the observer method keyboardWillHide(notification:), reset the bottom constraint of your UITextView.
main.swift
@objc func keyboardWillHide(notification: NSNotification) {
    textViewBottomConstraint.constant = 16 // 16 is the padding
}
126 chars
4 lines
  1. Make sure the UITextView is pinned to the bottom of the screen with a constraint (e.g., textViewBottomConstraint).

You can also adjust the position of other UI elements when the keyboard is shown by changing their constraints in the keyboardWillShow(notification:) method. And don't forget to remove the notification observers when the view controller is deallocated:

main.swift
deinit {
    NotificationCenter.default.removeObserver(self)
}
63 chars
4 lines

gistlibby LogSnag