The Question:
I have a ViewController that has a subclass with a UIScrollView in it.
In the scrollView there are 3 UITextFields. 2 of them with a numberPad keyboard and 1 with a UIPickerView keyboard.
The problem is that when the keyboards are presented, it hides the UITextFields. So what I'm trying to do is to move the UIViewController's view up when the keyboards are being shown.
What I've already tried:
I've searched this question on SO and I've found some answers, based on them I've wrote this code:
override func viewDidLoad() {
super.viewDidLoad()
//Keyboard notifications
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//MARK: - keyboards
@objc fileprivate func keyboardWillShow(notification: Notification) {
self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}
@objc fileprivate func keyboardWillHide(notification: Notification) {
self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}
fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
if self.controllerContentView.frame.origin.y == 0 {
self.controllerContentView.frame.origin.y = -keyboardSize.height
} else {
self.controllerContentView.frame.origin.y = 0
}
})
}
}
fileprivate func dismissKeyboard() {
self.view.endEditing(true)
}
//Touch handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismissKeyboard()
}
The problem with what I've tried:
Sometimes it works great, but sometimes the view "jumps" back up/"jumps" down and I can't understand why.
Does anybody see any problem with my code that can cause this bug?
Thank you!