To my understanding the object
parameter of the addObserver
method is the object you want to receive notifications from. Most of the time I see it as nil
(I assume this is because notifications of the specified type are wanted from all objects). In my particular case I have a text field at the top of the screen and at the bottom of the screen and I want the view to move up only when the user taps the bottom text field, not the top one. So I call the following method in viewWillAppear
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: self.bottomTextField)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: self.bottomTextField)
}
the keyboardWillShow:
and keyboardWillHide:
selectors call methods that do the repositioning of the view's frame. I tried leaving the object
parameter to be nil
but that would receive notifications from both text fields. I tried setting the object
parameter to self.bottomTextField
(as seen above) but that doesn't receive notifications from either text field. My question is twofold. First, am I understanding the addObserver
method correctly (especially the object
parameter) and second, why is it not registering notifications from self.bottomTextField
. Thanks!
Solution: I know this isn't the solution to the exact question I was asking but what I did in the end to make the view move up when only clicking on the bottom text field was the following:
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
and then in the keyboardWillShow:
method I have:
func keyboardWillShow(notification: NSNotification) {
if bottomTextField.editing { // only reset frame's origin if editing from the bottomTextField
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
Hopefully that helps!