Reputation: 123
I'm trying to move my whole view upwards to be able to see what the user is typing in a textfield. However, it works perfectly the first time as I want it to. However, when clicking on return key on the keyboard (to dismiss it), and then clicking on the textfield, I get the keyboard slightly over the textfield and not getting the same results as I do the first time. Why is this?
This is my code:
@IBOutlet weak var commentTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
commentTextField.delegate = self
//Keyboard listeners
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
commentTextField.resignFirstResponder()
return true
}
Upvotes: 0
Views: 71
Reputation: 1882
You are miss-calling the Variable.
UIKeyboardFrameBeginUserInfoKey
The key for an NSValue object containing a CGRect that identifies the starting frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.
UIKeyboardFrameEndUserInfoKey
The key for an NSValue object containing a CGRect that identifies the ending frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.
Therefore, what you need is to check the UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey.
Do the substitution and you may get it solved.
Upvotes: 1
Reputation: 100503
Replace
UIKeyboardFrameBeginUserInfoKey
with
UIKeyboardFrameEndUserInfoKey
Upvotes: 2