Yes, I've added the observer. The method is called when the keyboard appears. I even printed self.view.frame.origin.y from the method and it's what it's supposed to be -- a negative value to compensate for the keyboard. The code works except when the keyboard first appears after viewDidLoad makes the text field first responder, which causes the keyboard to appear. After the first time the code runs, when it runs after that, the code has the desired effect on the view.
I would like to run the code inside the keyboardWillShow method once in viewDidLoad, but I don't know how to get the keyboard height without using the sender parameter that is passed to keyboardWillShow. Do you know how I can do that? Below is the code in keyboardWillShow that defines the variable that holds the keyboard height:
let keyboardSize = (sender.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
Here is the entire keyboardWillShow method:
func keyboardWillShow(_ sender: Notification) {
if textFieldDataFileName.isFirstResponder {
let keyboardSize = (sender.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
var offset = keyboardSize.height - (self.view.frame.height - textFieldDataFileName.frame.origin.y - textFieldDataFileName.frame.height)
print("\toffset: \(offset)")
if offset > keyboardSize.height {
offset = keyboardSize.height
}
self.view.frame.origin.y = -offset
print("\ty: \(self.view.frame.origin.y)")
}
}