Bird
Raised Fist0
iOS Swiftmobile~15 mins

Keyboard management in iOS Swift - Deep Dive

Choose your learning style10 modes available
Overview - Keyboard management
What is it?
Keyboard management is how an app handles the on-screen keyboard that appears when a user types. It ensures that text fields or input areas stay visible and usable when the keyboard shows or hides. This prevents the keyboard from covering important parts of the app interface. Good keyboard management improves user experience by making typing smooth and frustration-free.
Why it matters
Without keyboard management, users often struggle because the keyboard hides the text they want to edit or buttons they need to tap. This can make apps feel broken or hard to use, causing users to leave or give up. Keyboard management solves this by adjusting the app layout dynamically, so users always see what they need while typing. It makes apps feel polished and professional.
Where it fits
Before learning keyboard management, you should understand basic iOS UI components like UITextField and UIViewController. After mastering keyboard management, you can explore advanced input handling like custom input views, text input accessory views, and accessibility improvements for typing.
Mental Model
Core Idea
Keyboard management is about moving or resizing app content so the keyboard never blocks what the user needs to see or interact with.
Think of it like...
Imagine you are reading a book and someone holds a big board in front of your eyes. To keep reading, you slide the book up or move your head so the words stay visible. Keyboard management is like sliding the book up when the board (keyboard) appears.
┌───────────────────────────────┐
│           Screen              │
│ ┌───────────────┐             │
│ │ Text Field    │             │
│ └───────────────┘             │
│                               │
│ ──────────────── Keyboard ─── │
│                               │
│ (Keyboard appears, app moves) │
└───────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat triggers the keyboard
🤔
Concept: Learn what causes the keyboard to appear and disappear in iOS apps.
When a user taps on a UITextField or UITextView, iOS automatically shows the keyboard. When the user finishes typing or taps outside, the keyboard hides. These events are automatic but apps can listen to notifications to know when the keyboard appears or disappears.
Result
You understand that keyboard visibility depends on user interaction with input fields and that the system sends notifications about these changes.
Knowing the keyboard triggers helps you react properly and prepare your app UI to adjust when typing starts or ends.
2
FoundationKeyboard notifications in iOS
🤔
Concept: iOS sends notifications when the keyboard shows, hides, or changes size.
UIKit posts notifications like UIKeyboardWillShowNotification, UIKeyboardWillHideNotification, and UIKeyboardWillChangeFrameNotification. You can observe these notifications to get keyboard size and animation info. This lets your app respond smoothly to keyboard changes.
Result
You can detect exactly when the keyboard appears or disappears and get its height and animation duration.
Understanding keyboard notifications is the foundation for adjusting your UI dynamically and smoothly.
3
IntermediateAdjusting view with keyboard frame
🤔Before reading on: do you think moving the entire view up or resizing only the scroll area is better? Commit to your answer.
Concept: Use keyboard frame info to move or resize views so input fields stay visible.
When the keyboard appears, get its height from the notification. Then move your main view up by that height or reduce the scroll view's content inset. This prevents the keyboard from covering the active text field. When the keyboard hides, reset the view or insets.
Result
The input field stays visible above the keyboard, and the user can see what they type.
Knowing how to adjust views based on keyboard size prevents hidden inputs and improves typing experience.
4
IntermediateUsing UIScrollView for keyboard management
🤔Before reading on: do you think UIScrollView helps only with scrolling or also with keyboard handling? Commit to your answer.
Concept: UIScrollView can automatically scroll content to keep inputs visible when keyboard appears.
Wrap your input fields inside a UIScrollView. When the keyboard shows, increase the scroll view's bottom content inset by the keyboard height. Then scroll to the active input field. When the keyboard hides, reset the inset. This approach works well for forms with many inputs.
Result
The scroll view moves content up smoothly, so the active field is never hidden by the keyboard.
Using UIScrollView leverages built-in scrolling to handle keyboard overlap elegantly, especially for long forms.
5
IntermediateDismissing keyboard on tap outside
🤔
Concept: Make the keyboard hide when the user taps outside input fields.
Add a UITapGestureRecognizer to the main view that calls view.endEditing(true). This tells the app to resign first responder status from any input, hiding the keyboard. This improves usability by letting users dismiss the keyboard easily.
Result
Tapping outside the keyboard or input fields closes the keyboard smoothly.
Allowing easy dismissal of the keyboard prevents user frustration and keeps the interface clean.
6
AdvancedHandling keyboard with safe area and rotation
🤔Before reading on: do you think keyboard size and position stay the same in all device orientations? Commit to your answer.
Concept: Adjust keyboard management to respect safe area insets and device rotation changes.
The keyboard frame changes with device orientation and safe area (like iPhone notch). Use the keyboard frame from notifications and convert it to your view's coordinate system. Also, update your adjustments on rotation events to keep inputs visible and avoid layout glitches.
Result
Your app layout adapts correctly to keyboard size and position in all orientations and devices.
Accounting for safe areas and rotation prevents UI bugs and ensures a consistent user experience across devices.
7
ExpertCustom input accessory views and keyboard avoidance
🤔Before reading on: do you think input accessory views affect keyboard size or layout? Commit to your answer.
Concept: Input accessory views add custom toolbars above the keyboard and affect keyboard layout and management.
You can add a custom UIView as inputAccessoryView to UITextField or UITextView. This view appears above the keyboard and changes the keyboard's effective height. Your keyboard management code must consider this extra height to avoid overlapping. Also, input accessory views can provide custom buttons or controls for better input experience.
Result
Your app correctly adjusts for keyboards with accessory views, keeping inputs and controls visible.
Understanding how accessory views affect keyboard layout helps build richer input interfaces without layout bugs.
Under the Hood
When a text input becomes first responder, iOS creates and displays the keyboard window above the app's window. The system sends notifications with the keyboard's frame and animation info. The app can listen and adjust its views accordingly. The keyboard is a separate window managed by the system, so the app must move or resize its own views to avoid overlap.
Why designed this way?
iOS separates the keyboard as a system-managed window to keep input consistent and secure across apps. Notifications allow apps to react without controlling the keyboard directly. This design balances system control with app flexibility, avoiding conflicts and ensuring smooth animations.
App Window
┌─────────────────────┐
│                     │
│  Your Views          │
│  ┌───────────────┐  │
│  │ UITextField   │  │
│  └───────────────┘  │
│                     │
└─────────────────────┘

Keyboard Window (System)
┌─────────────────────┐
│  Keyboard UI        │
│  ┌───────────────┐  │
│  │ Keys & Layout │  │
│  └───────────────┘  │
└─────────────────────┘

Notifications sent:
UIKeyboardWillShowNotification
UIKeyboardWillHideNotification
UIKeyboardWillChangeFrameNotification
Myth Busters - 4 Common Misconceptions
Quick: Does the keyboard automatically push your app's views up when it appears? Commit yes or no.
Common Belief:The keyboard automatically moves app views so inputs are never hidden.
Tap to reveal reality
Reality:The keyboard appears as a separate window and does not move or resize your app's views automatically. The app must listen to keyboard notifications and adjust its views manually.
Why it matters:Assuming automatic adjustment leads to hidden inputs and broken user experience.
Quick: Is it enough to just move the view up by a fixed amount when the keyboard appears? Commit yes or no.
Common Belief:Moving the view up by a fixed height always works for keyboard management.
Tap to reveal reality
Reality:Keyboard height varies by device, orientation, and presence of input accessory views. Fixed values cause layout bugs or hidden inputs on some devices.
Why it matters:Using fixed values causes inconsistent UI and frustrates users on different devices.
Quick: Does dismissing the keyboard require special buttons only? Commit yes or no.
Common Belief:Users can only dismiss the keyboard by tapping a done button or similar control.
Tap to reveal reality
Reality:Adding a tap gesture recognizer to the background to call endEditing(true) lets users dismiss the keyboard by tapping outside inputs, which is more natural.
Why it matters:Not enabling tap-to-dismiss leads to poor usability and user frustration.
Quick: Does the keyboard frame always stay the same regardless of device orientation? Commit yes or no.
Common Belief:Keyboard size and position are constant and do not change with rotation.
Tap to reveal reality
Reality:Keyboard frame changes with device orientation and safe area insets, so layout adjustments must be dynamic.
Why it matters:Ignoring orientation causes layout glitches and hidden inputs after rotation.
Expert Zone
1
Keyboard notifications provide animation duration and curve info that you can use to synchronize your UI changes with the keyboard's animation for smooth transitions.
2
Input accessory views increase the keyboard's effective height, so failing to account for them causes subtle layout bugs where inputs are still partially hidden.
3
Using UIResponder's inputAccessoryView property allows adding custom toolbars or controls that improve input UX but require careful layout management.
When NOT to use
Keyboard management techniques described here are not needed for apps that do not use text input or use only system modal input views. For complex custom keyboards or input methods, consider building custom input views or using third-party libraries specialized for keyboard handling.
Production Patterns
In production, apps often combine UIScrollView insets adjustment with tap gesture recognizers to dismiss the keyboard. They also use keyboard animation info to animate layout changes smoothly. Complex forms use libraries or custom helpers to manage keyboard avoidance consistently across screens.
Connections
Event-driven programming
Keyboard management relies on reacting to system events (notifications) to update UI.
Understanding event-driven patterns helps grasp how keyboard notifications trigger UI changes asynchronously.
Human-computer interaction (HCI)
Keyboard management improves usability by adapting interface to user input context.
Knowing HCI principles explains why visible inputs and easy dismissal reduce user frustration.
Ergonomics
Keyboard management ensures comfortable interaction by preventing blocked views and awkward typing postures.
Ergonomics teaches that adapting UI to physical constraints improves user comfort and efficiency.
Common Pitfalls
#1Keyboard covers the text field, making it invisible while typing.
Wrong approach:Ignoring keyboard notifications and not adjusting view positions or insets.
Correct approach:Observe UIKeyboardWillShowNotification and UIKeyboardWillHideNotification notifications and adjust scroll view insets or move views accordingly.
Root cause:Assuming the system automatically handles keyboard overlap without app intervention.
#2Keyboard adjustment uses fixed height values causing layout issues on different devices.
Wrong approach:Moving view up by a hardcoded 216 points when keyboard appears.
Correct approach:Use keyboard frame from notification to get exact height dynamically and adjust layout.
Root cause:Not accounting for device variation and keyboard accessory views.
#3User cannot dismiss keyboard by tapping outside input fields.
Wrong approach:No tap gesture recognizer added to dismiss keyboard on background tap.
Correct approach:Add UITapGestureRecognizer to view that calls view.endEditing(true) to hide keyboard.
Root cause:Overlooking natural user behavior for dismissing keyboard.
Key Takeaways
Keyboard management ensures that input fields remain visible and accessible when the on-screen keyboard appears.
iOS sends notifications about keyboard appearance and size changes, which apps must observe to adjust their UI dynamically.
Using UIScrollView and adjusting its content inset is a common and effective way to handle keyboard overlap for forms.
Allowing users to dismiss the keyboard by tapping outside inputs improves usability and feels natural.
Accounting for device orientation, safe areas, and input accessory views prevents layout bugs and ensures a polished user experience.

Practice

(1/5)
1. What is the main purpose of managing the keyboard in an iOS app?
easy
A. To disable typing in text fields
B. To keep input fields visible when the keyboard appears
C. To change the keyboard color
D. To automatically save user input

Solution

  1. Step 1: Understand keyboard impact on UI

    The keyboard can cover input fields, making them hard to see or use.
  2. Step 2: Purpose of keyboard management

    Managing the keyboard ensures input fields stay visible and accessible when typing.
  3. Final Answer:

    To keep input fields visible when the keyboard appears -> Option B
  4. Quick Check:

    Keyboard management = keep inputs visible [OK]
Hint: Keyboard management keeps inputs visible when typing [OK]
Common Mistakes:
  • Thinking keyboard management changes keyboard color
  • Believing it disables typing
  • Assuming it auto-saves input
2. Which Swift method is used to dismiss the keyboard when tapping outside a UITextField?
easy
A. textField.resignFirstResponder()
B. textField.becomeFirstResponder()
C. textField.showKeyboard()
D. textField.hideKeyboard()

Solution

  1. Step 1: Identify method to dismiss keyboard

    Calling resignFirstResponder() on a UITextField tells it to stop being active, hiding the keyboard.
  2. Step 2: Check other options

    becomeFirstResponder() shows keyboard; showKeyboard() and hideKeyboard() do not exist in UIKit.
  3. Final Answer:

    textField.resignFirstResponder() -> Option A
  4. Quick Check:

    Dismiss keyboard = resignFirstResponder() [OK]
Hint: Use resignFirstResponder() to hide keyboard [OK]
Common Mistakes:
  • Using becomeFirstResponder() which shows keyboard
  • Trying non-existent methods like hideKeyboard()
  • Not calling any method to dismiss keyboard
3. 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
  }
}
medium
A. Nothing happens when keyboard appears
B. The keyboard is hidden automatically
C. The scroll view scrolls to top
D. The scroll view's bottom inset increases to avoid keyboard overlap

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]
Hint: Keyboard show notification adjusts scroll inset bottom [OK]
Common Mistakes:
  • Thinking keyboard hides automatically
  • Assuming scroll view scrolls to top
  • Ignoring contentInset adjustment
4. What is wrong with this Swift code for dismissing the keyboard?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  view.endEditing(true)
}
medium
A. endEditing(true) does not dismiss keyboard
B. TouchesBegan is not called on UIViewController
C. It should call super.touchesBegan to propagate touch events
D. The method signature is incorrect

Solution

  1. Step 1: Check method override

    Overriding touchesBegan requires calling super.touchesBegan to allow normal touch handling.
  2. Step 2: Identify missing call

    The code misses super.touchesBegan, which can cause touch events to stop propagating.
  3. Final Answer:

    It should call super.touchesBegan to propagate touch events -> Option C
  4. Quick Check:

    Override touchesBegan must call super [OK]
Hint: Always call super in overridden touchesBegan [OK]
Common Mistakes:
  • Not calling super.touchesBegan
  • Thinking endEditing(true) doesn't dismiss keyboard
  • Using wrong method signature
5. You want to move the view up when the keyboard appears and move it back down when it hides. Which approach correctly handles this in Swift?
hard
A. Listen to keyboardWillShow and keyboardWillHide notifications, adjust view frame accordingly
B. Only listen to keyboardDidShow notification and adjust view frame
C. Use a timer to check keyboard height every second and move view
D. Change the keyboard type to avoid covering the view

Solution

  1. Step 1: Understand keyboard notifications

    keyboardWillShow and keyboardWillHide notify before keyboard appears/disappears, allowing smooth UI changes.
  2. Step 2: Adjust view frame on both notifications

    Adjusting view frame up on show and back down on hide keeps UI consistent and responsive.
  3. Step 3: Evaluate other options

    Listening only to keyboardDidShow is late; timer wastes resources; changing keyboard type doesn't solve overlap.
  4. Final Answer:

    Listen to keyboardWillShow and keyboardWillHide notifications, adjust view frame accordingly -> Option A
  5. Quick Check:

    Use willShow and willHide notifications for UI moves [OK]
Hint: Use willShow and willHide notifications to move views [OK]
Common Mistakes:
  • Using only keyboardDidShow notification
  • Polling keyboard height with timer
  • Trying to change keyboard type to fix layout
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard