Bird
0
0

Given this Swift code snippet, what happens when the keyboard appears?

medium📝 ui behavior Q13 of 15
iOS Swift - User Input and Forms
Given this Swift code snippet, what happens when the keyboard appears?
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)

@objc func keyboardWillShow(notification: NSNotification) {
  if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
    scrollView.contentInset.bottom = keyboardSize.height
  }
}
ANothing happens when keyboard appears
BThe keyboard is hidden automatically
CThe scroll view scrolls to top
DThe scroll view's bottom inset increases to avoid keyboard overlap
Step-by-Step Solution
Solution:
  1. Step 1: Understand notification observer

    The code listens for keyboard showing and calls keyboardWillShow function.
  2. Step 2: Adjust scroll view inset

    Inside keyboardWillShow, it sets scrollView.contentInset.bottom to keyboard height, pushing content up.
  3. Final Answer:

    The scroll view's bottom inset increases to avoid keyboard overlap -> Option D
  4. Quick Check:

    Keyboard show adjusts scroll inset [OK]
Quick Trick: Keyboard show notification adjusts scroll inset bottom [OK]
Common Mistakes:
  • Thinking keyboard hides automatically
  • Assuming scroll view scrolls to top
  • Ignoring contentInset adjustment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes