UIKitMidOpen-ended
How do you handle keyboard appearance and dismissal?
Explanation & Code
Answer: Subscribe to keyboard notifications to adjust your layout when the keyboard appears or hides, so it doesn't cover your input fields.
Code Example:
class FormViewController: UIViewController {
var bottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setupBottomConstraint()
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
else { return }
UIView.animate(withDuration: duration) {
self.bottomConstraint.constant = -keyboardFrame.height
self.view.layoutIfNeeded()
}
}
@objc func keyboardWillHide(_ notification: Notification) {
UIView.animate(withDuration: 0.3) {
self.bottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
}
SwiftUI alternative: .ignoresSafeArea(.keyboard) or ScrollView handles it automatically.
Rate your understanding: