So I have a screen with 2 text fields. When they are being edited, I want the keyboard to sit undeeath the textfield and scroll up when the next field is selected. I also wanted to hide the keyboard if the view was tapped. I had this working a couple of weeks ago using the following code:
in viewDidLoad:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NetworkSetupViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
For the text fields, I have the textFieldShouldRetu method defined as follows:
func textFieldShouldRetu(textField: UITextField) -> Bool {
if(textField == f1){
textField.resignFirstResponder()
f2.becomeFirstResponder()
}
else if(textField == f2){
textField.resignFirstResponder()
nextButtonClicked(self)
}
else{
retu false
}
retu true
}
And finally, I defined the textFieldDidBegin/EndEditing methods as follows:
func textFieldDidBeginEditing(textField: UITextField) { // became first responder
//move textfields up
let myScreenRect: CGRect = UIScreen.mainScreen().bounds
let keyboardHeight : CGFloat = 216
UIView.beginAnimations( "animateView", context: nil)
//let movementDuration:NSTimeInterval = 0.35
var needToMove: CGFloat = 0
var frame : CGRect = self.view.frame
if (textField.frame.origin.y + textField.frame.size.height + self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight)) {
needToMove = (textField.frame.origin.y + textField.frame.size.height + self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight);
}
frame.origin.y = -needToMove
self.view.frame = frame
UIView.commitAnimations()
}
func textFieldDidEndEditing(textField: UITextField) {
//move textfields back down
UIView.beginAnimations( "deanimateView", context: nil)
//var movementDuration:NSTimeInterval = 0.35
var frame : CGRect = self.view.frame
frame.origin.y = 0
self.view.frame = frame
UIView.commitAnimations()
}
However, the text fields move up, and the retu key works as expected, however the view never animates back down. I have checked with the debugger that the didEndEditing method gets fired, but even when I step through it, I never see it move back down.
Like I said, I thought I had this working properly a few weeks ago, may some minor UI changes and suddenly BOOM, it's broken. Story of our lives.
Thank you for any help and time.
