Keyboard hides on rotation

2019-06-24 08:33发布

问题:

I'm working on an iPad application. In one of it's views, i have a subview which appears and disappears on button tap event. The subview contains a UITextView. By default i make it the first responder so that the keyboard appears as soon as the view appears. The subview also disappears when UIKeyboardWillHideNotification is fired i.e. keyboard is hidden.

Now, the problem is that as soon as the application is rotated, UIKeyboardWillHideNotification is fired by the system, which in turn make the subview disappear. I want the keyboard to remain on screen.

What's going on, and how can i fix it!?

Note: Both the view and subview have separate view controllers. UIKeyboardWillHideNotification is received in subview's view controller class.

回答1:

You can declare a BOOL variable in shouldAutoRotate method and that is set when it is called and then in the selector method for showing and hiding the subview you can use a simple if condition that weather view is rotated or not.

like this:

if(viewRotated)
{
    subView.hidden = YES;
}
viewRotated = NO;

Edit Part:
I am not sure whats going on in this code but its working perfectly in one of my apps who's ipad coding was done by my friend.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(UIInterfaceOrientationIsPortrait(interfaceOrientation))
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:) 
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
    }
    else
    {

        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:UIKeyboardWillShowNotification 
                                                      object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:UIKeyboardWillShowNotification 
                                                      object:nil];
    }
    return YES;
}

And you can add the notification again if your UIKeyboardWillHideNotification is not fired by add those notification again in this method.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation


回答2:

You can use a BOOL variable to recording whether it's rotating. Then you can do nothing when it's rotating.