Rishi
Rishi

Reputation: 3549

handleKeyboardWillShow notification Handling

I have a Tableview in inside a viewcontroller. I have added following code to get keyboard notifications

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

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

And on keyboard show i am scrolling my table to bottom.

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

    [self scrollToBottomAnimated:YES];
}

But i have a textview in my view controller as well. So when i click on textview the handleKeyboardWillShow method is called as well resulting unnecessary scrolling my tableview which i do not need if textview is clicked.

Can some one please help me figure out how to detect from which sender handleKeyboardWillShow is called.

Thanks

Upvotes: 0

Views: 114

Answers (2)

Chris Feher
Chris Feher

Reputation: 111

I would register for keyboardWillChange - which covers both showing and hiding. You can get the keyboard rect and adjust your content offset based on the keyboard's location. Note: You can animate the change in content offset - I just didn't do it in this answer.

In your textfield delegate methods willBeginEditing and didEndEditing, you can set the state variable called currentTextField.

-(void)keyboardWillChange:(NSNotification *)notification {
        keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

        CGPoint currentFieldPoint = [currentTextField convertPoint:currentTextField.frame.origin toView:self.view];

        if(keyboardRect.origin.y < currentFieldPoint.y + currentTextField.frame.size.height){
            //move stuff here
            [[self tableView] setContentOffset:CGPointMake(0, [self tableView].contentOffset.y + offsetValue)];

        }

    }

Upvotes: 0

Logan
Logan

Reputation: 53142

You can do it by checking who is first responder.

- (void)handleKeyboardWillShow:(NSNotification *)notification
{
    if ([textFieldForScrolling isFirstResponder]) {
        [self scrollToBottomAnimated:YES];
    } else {
        NSLog(@"Is a different text input");
    }
}

Let me know if you need more explanation.

Upvotes: 1

Related Questions