UIKeyboardWillShowNotification, UIKeyboardWillHideNotification and NSNotificationCenter problem between iOS versions

CristiC picture CristiC · Jul 22, 2011 · Viewed 15.5k times · Source

I have several UITextFields on my view (each inside a UITableViewCell). When the keyboard is fired from any of the textfields, I need to make some animations, mainly to change the frame of the UITableView. The same must happen when the keyboard will hide.

I have done the animation, so this is not the issue here.

Now, I use NSNotificationCenter to catch displaying/hiding of the keyboard:

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

The problem is when the keyboard is visible (a textfield is used) and I press inside another textfield. Usually for this thing keyboard will not hide, but will stay visible.

It works fine in iOS 4, but the problem comes in 3.1.3 (this is the version that I can test - possibly any version below 3.2). In versions older than 3.2 changing focus from a textfield directly to another textfield will fire the UIKeyboardWillHideNotification and UIKeyboardWillShowNotification.

Anyone knows a way to perform some animation when the keyboard will really show/hide, without the NSNotificationCenter?

Or how can I overcome this issue with versions lower than 3.2?

Thanks.

Answer

Mihai Fratu picture Mihai Fratu · Jul 25, 2011

What you can do is set the textfield's/textview's delegate to the current view controller and implement these 2 methods

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _keyboardWillHide = NO;
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    _keyboardWillHide = NO;
    return YES;    
}

After that in your method that get's triggered by the UIKeyboardWillHideNotification notification you can do something like

if (_keyboardWillHide) {
    // No other textfield/textview was selected so you can animate the tableView
    ...
}
_keyBoardWillHide = YES;

Let me know if that works for you.