Complete the code to dismiss the keyboard when the user taps outside the text field.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.[1]() }
Calling endEditing(true) on the view dismisses the keyboard by ending editing on the current first responder.
Complete the code to move the view up 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 { self.view.frame.origin.y = [1] } }
To move the view up, subtract the keyboard height from the view's origin y position.
Fix the error in the code to reset the view position when the keyboard hides.
@objc func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y = [1]
}Resetting the view's origin y to 0 moves it back to its original position.
Fill both blanks to add observers for keyboard show and hide notifications.
NotificationCenter.default.addObserver(self, selector: #selector([1]), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector([2]), name: UIResponder.keyboardWillHideNotification, object: nil)
Use keyboardWillShow and keyboardWillHide selectors to respond to keyboard appearance and disappearance.
Fill all three blanks to properly remove keyboard observers in deinit.
deinit {
NotificationCenter.default.[1](self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.[2](self, name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.[3](self)
}Use removeObserver to unregister from notifications to avoid memory leaks.