Convert UIKeyboardFrameEndUserInfoKey to View or Window Coordinates

Ser Pounce picture Ser Pounce · Mar 14, 2013 · Viewed 16.6k times · Source

For the constant UIKeyboardFrameEndUserInfoKey, in the Apple docs it says:

These coordinates do not take into account any rotation factors applied to the window’s contents as a result of interface orientation changes. Thus, you may need to convert the rectangle to window coordinates (using the convertRect:fromWindow: method) or to view coordinates (using the convertRect:fromView: method) before using it.

So if I use [view1 convertRect:rect fromView:view2]

What would I insert for the above parameters to get it to convert the rotation values correctly? ie:

view1 = ? rect = ? (the keyboard frame I'm assuming) view2 = ?

Been trying some things and getting some funny stuff.

Answer

matt picture matt · Mar 22, 2013

The first view should be your view. The second view should be nil, meaning window/screen coordinates. Thus:

NSDictionary* d = [notification userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
r = [myView convertRect:r fromView:nil];

Now you have the rect that the keyboard will occupy, in terms of your view. If your view is the current view controller's view (or a subview thereof), rotation and so forth are now accounted for.