Bird
Raised Fist0
iOS Swiftmobile~20 mins

Keyboard management in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Keyboard Management Screen
This screen has a text field that moves up when the keyboard appears so it is not hidden. It also dismisses the keyboard when tapping outside the text field.
Target UI
-------------------------
| Keyboard Management   |
|-----------------------|
|                       |
| Enter text: [       ] |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
-------------------------
Add a UITextField near the bottom of the screen.
Move the view up when the keyboard appears so the text field is visible.
Move the view back down when the keyboard disappears.
Dismiss the keyboard when tapping anywhere outside the text field.
Starter Code
iOS Swift
import UIKit

class KeyboardManagementViewController: UIViewController {

    let textField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Setup text field
        textField.borderStyle = .roundedRect
        textField.placeholder = "Enter text"
        textField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(textField)

        NSLayoutConstraint.activate([
            textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
            textField.heightAnchor.constraint(equalToConstant: 40)
        ])

        // TODO: Add keyboard notifications and tap gesture recognizer
    }

    // TODO: Add keyboard show/hide handlers
    
    // TODO: Add tap gesture handler to dismiss keyboard
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import UIKit

class KeyboardManagementViewController: UIViewController {

    let textField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Setup text field
        textField.borderStyle = .roundedRect
        textField.placeholder = "Enter text"
        textField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(textField)

        NSLayoutConstraint.activate([
            textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
            textField.heightAnchor.constraint(equalToConstant: 40)
        ])

        // Register keyboard notifications
        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)

        // Add tap gesture recognizer to dismiss keyboard
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tapGesture.cancelsTouchesInView = false
        view.addGestureRecognizer(tapGesture)
    }

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

        let keyboardHeight = keyboardFrame.height

        // Move view up by keyboard height
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardHeight
        }
    }

    @objc func keyboardWillHide(notification: Notification) {
        // Move view back to original position
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y = 0
        }
    }

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

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

We add observers for keyboard show and hide notifications to know when the keyboard appears and disappears. When the keyboard shows, we get its height and move the whole view up by that height so the text field stays visible above the keyboard. When the keyboard hides, we reset the view position back to normal.

We also add a tap gesture recognizer to the main view. When the user taps anywhere outside the text field, this gesture triggers and dismisses the keyboard by ending editing on the view.

This approach keeps the UI simple and user-friendly by preventing the keyboard from covering the text field and allowing easy dismissal.

Final Result
Completed Screen
-------------------------
| Keyboard Management   |
|-----------------------|
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
| Enter text: [       ] |
|                       |
-------------------------
When the user taps the text field, the keyboard appears and the whole view moves up so the text field is not hidden.
When the user taps outside the text field, the keyboard dismisses and the view moves back down.
Stretch Goal
Add smooth animation when the view moves up and down with the keyboard.
💡 Hint
Use UIView.animate with the keyboard animation duration and curve from notification userInfo.

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