I'm having a problem with keyboard textfield. I'm working on swift 4 in iOS 9.2
I have a login screen which does have a lot of constraints (to be adaptable for every screen). In my login screen, I have a username and password textfield.
The problem is that when I launch the application on my IPad, the keyboard appears in center of the associated textField. Moreover, the observer won't work : When I use debugger, I never get inside the observers
But when I launch on simulator, everything works perfectly.
#My object life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
# My textfield delegates and observers
extension LoginViewController {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@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 let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
}
And for my textfield storyboard configuration, here is it
So what didn't I understood ?
- Is the keyboard also dependants to textfield constraints ?
- Why the observers aren't working on iPad but works in simulation ?
- how can I move the keyboard programatically ?