Sobes.tech
Middle

What can be done if the keyboard hides important interface elements when it appears?

sobes.tech AI

Answer from AI

Use NotificationCenter to monitor the appearance (UIKeyboardWillShowNotification) and hiding (UIKeyboardWillHideNotification) of the keyboard. In the handlers for these events, you can adjust the insets or shift the content of a ScrollView or TableView.

Alternative approaches:

  • Use the IQKeyboardManagerSwift library. It automatically manages content shifting.
  • In SwiftUI, use the .ignoresSafeArea(.keyboard, edges: .bottom) modifier.

Example code for manual handling via NotificationCenter:

// Subscribe to notifications
NotificationCenter.default.addObserver(self,
                                       selector: #selector(keyboardWillShow(_:)),
                                       name: UIResponder.keyboardWillShowNotification,
                                       object: nil)

NotificationCenter.default.addObserver(self,
                                       selector: #selector(keyboardWillHide(_:)),
                                       name: UIResponder.keyboardWillHideNotification,
                                       object: nil)

// Handler for keyboard appearance
@objc func keyboardWillShow(_ notification: Notification) {
    guard let userInfo = notification.userInfo,
          let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
        return
    }

    // Animate inset change
    let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardFrame.height, right: 0.0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets

    // Scroll to active text field
    if let activeField = activeTextField { // activeTextField is the currently active field
        let activeFieldRect = scrollView.convert(activeField.bounds, from: activeField)
        scrollView.scrollRectToVisible(activeFieldRect, animated: true)
    }
}

// Handler for keyboard hiding
@objc func keyboardWillHide(_ notification: Notification) {
    let contentInsets = UIEdgeInsets.zero
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}

// Don't forget to remove observers upon deinitialization
deinit {
    NotificationCenter.default.removeObserver(self)
}

Key properties from the notification's userInfo dictionary:

Key Type Description
UIResponder.keyboardFrameBeginUserInfoKey CGRect Initial frame of the keyboard in screen coordinates.
UIResponder.keyboardFrameEndUserInfoKey CGRect Final frame of the keyboard in screen coordinates.
UIResponder.keyboardAnimationDurationUserInfoKey Double Duration of the keyboard appearance/disappearance animation.
UIResponder.keyboardAnimationCurveUserInfoKey UInt (RAW UIView.AnimationCurve) Animation curve.
What can be done if the keyboard hides important… - sobes.tech