UITextField and Keyboard Notifications - strange order

Bourne picture Bourne · Dec 17, 2013 · Viewed 10.1k times · Source

So I've set up a notification for the keyboard appearance event. Now let us consider a UITextView and a UITextField.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

The selector is:

- (void)keyboardWillShow:(NSNotification *)notification {

        keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
}

In case of a UITextView, the delegate method - (void)textViewDidBeginEditing:(UITextView *)textView is fired AFTER the keyboardWillShow: method. So keyboardSize has the keyboard's actual size and I'm able to use that inside the textview delegate method.

However in case of a UITextField, the corresponding delegate method - (void)textFieldDidBeginEditing:(UITextField *)textField is fired BEFORE the keyboardWillShow: method.

Why is this so? How do I get the keyboard's CGSize in the textfield's case as now it just returns zero because the textfield delegate is called first and not the keyboard selector.

Answer

Brett George picture Brett George · Dec 30, 2014

I've had this same problem. Try using:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView