screenMonkey MonkeyMan
screenMonkey MonkeyMan

Reputation: 423

The height on my soft keyboard changes when triggered multiple times

I have an observed method that trigger when the soft keyboard is shown. It works fine, but for some reason the height of the soft keyboard changes after it has been hidden, then presented for the second time. I can't find a reason for this and there doesn't seem to be anything in the hide-delegate that changes its value. What causes this? I have worked around the problem by storing the height then using it the second time, but I would like to know the cause of this issue.

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];

    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect visibleRect = self.view.frame;

    if (_storedKeyboardHeight.size.height == 0) {
        _storedKeyboardHeight.size.height = keyboardSize.height;
    }

    visibleRect.size.height = _storedKeyboardHeight.size.height;
    visibleRect.origin.y = self.view.height - visibleRect.size.height;

    CGRect rectOfCellInTableView = [self.loginTableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];

    //This changes the second time
    NSLog(@"🦁 %f", keyboardSize.height);
    //so I store the original value here
    NSLog(@"🦁 %@", CGRectCreateDictionaryRepresentation(_storedKeyboardHeight));

    if ((rectOfCellInTableView.origin.y + rectOfCellInTableView.size.height) > visibleRect.origin.y){
        CGPoint scrollPoint = CGPointMake(0.0, (rectOfCellInTableView.origin.y + rectOfCellInTableView.size.height) - visibleRect.origin.y + 50);
        [self.loginTableView setContentOffset:scrollPoint animated:YES];
    }
}

First time the height is 291, second time it's 233.

Upvotes: 0

Views: 130

Answers (1)

matt
matt

Reputation: 535306

The problem is that you are examining the wrong frame:

UIKeyboardFrameBeginUserInfoKey

When the keyboard is shown, what its frame height is at the beginning of the showing process is of no interest to you. What you want to know is the frame at the end of the showing process:

UIKeyboardFrameEndUserInfoKey

Also, it looks like you are getting notified of the wrong thing. You have not shown what notification you are registered for, but the name of your method, keyboardWasShown, suggests that your are getting notified when the keyboard did show. That's too late; this notification is almost never of any interest. You want to know when the keyboard will show.

Upvotes: 1

Related Questions