Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIKeyboardWillShowNotification, UIKeyboardWillHideNotification and NSNotificationCenter problem between iOS versions

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.

like image 827
CristiC Avatar asked Jul 22 '11 19:07

CristiC


3 Answers

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.

like image 79
Mihai Fratu Avatar answered Nov 15 '22 14:11

Mihai Fratu


Rather than avoid the notifications, you can set an NSTimer for 0.1 second to do your animations in one, and in the other, cancel the timer, that way if you get UIKeyboardWillHide and UIKeyboardWillShow both at once, you'll get a chance to cancel the timer. If you don't get both, the timer will reach zero and the animations will be carried out.

like image 36
Alex Gosselin Avatar answered Nov 15 '22 14:11

Alex Gosselin


Consider using the UITextFieldDelegate protocol. The method textFieldShouldBeginEditing: will fire off before the notification and it will fire off everytime you go into the text field.

like image 36
Steve Yung Avatar answered Nov 15 '22 12:11

Steve Yung