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.