JMD
JMD

Reputation: 1590

Getting the frame of the keyboard at the window level

I am trying to get the coordinates of the frame of the keyboard at window level to be compared with a TableCell to make minor adjustments in scrolling so a selected TextField in the cell wont be behind the keyboard or the header.

However I am having issue getting the x,y coordinates for the keyboard at window level, they simply return 0,0 (origin) which is not true. Or if it is, is not what I need.

I am using the lines:

CGRect keyboardFrame = [self.view.window convertRect:_numericKeyboardView.frame toView:nil];
NSLog(@"Keyboard Frame: %f, %f, %f, %f", keyboardFrame.origin.x, keyboardFrame.origin.y, keyboardFrame.size.width, keyboardFrame.size.height);

which produces the output(for portrait):

Keyboard Frame: 0.000000, 0.000000, 768.000000, 264.000000

when it should be more like:

Keyboard Frame: 415.000000, 0.000000, 768.000000, 264.000000  

Any ideas on how to get the correct keyboard coordinates?

Upvotes: 1

Views: 2015

Answers (3)

XJones
XJones

Reputation: 21967

Your question is misleading. It sounds like your "keyboard" is a custom view , not the system keyboard. The question should be "getting the frame of a view in window coordinates". The convertRect:toView method will work but you have it backwards.

Change your code to:

CGRect keyboardFrame = [_numericKeyboardView convertRect:_numericKeyboardView.bounds 
                                                  toView:self.view.window];

Upvotes: 0

ehope
ehope

Reputation: 516

If you want to do it this way, you may be sending convertRect:toView: to the wrong receiver. Do [_numericKeyboardView convertRect:_numericKeyboardView.bounds toView:nil];

Upvotes: 1

Mert
Mert

Reputation: 6065

From http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

You need to register for keyboard notification like

 [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];

then

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGRect kbFrame = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
}

And do not forget to remove self form notification center in your dealloc method

Upvotes: 2

Related Questions