将UIKeyboardFrameEndUserInfoKey转换为视图或窗口坐标

Ser*_*nce 27 iphone cocoa-touch uiview uikeyboard ios

对于常数UIKeyboardFrameEndUserInfoKey,在Apple文档中它说:

这些坐标不考虑由于界面方向改变而应用于窗口内容的任何旋转因子.因此,您可能需要在使用之前将矩形转换为窗口坐标(使用convertRect:fromWindow:方法)或查看坐标(使用convertRect:fromView:方法).

所以,如果我使用 [view1 convertRect:rect fromView:view2]

我将为上述参数插入什么以使其正确转换旋转值?即:

view1 =?rect =?(我假设键盘架)view2 =?

一直在尝试一些事情并得到一些有趣的东西.

mat*_*att 68

第一个视图应该是您的视图.第二个视图应为零,表示窗口/屏幕坐标.从而:

NSDictionary* d = [notification userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
r = [myView convertRect:r fromView:nil];
Run Code Online (Sandbox Code Playgroud)

现在你有了键盘占据的矩形,就你的视图而言.如果您的视图是当前视图控制器的视图(或其子视图),则现在考虑旋转等.

  • +1,但我认为这只有在`myView`代表视图控制器的根视图时才有用.如果它没有,而myView是一个像`{100,100,200,200}`的子视图怎么办? (4认同)

Dav*_*dek 23

我尝试了接受的答案,发现它实际上并没有在视图中提供键盘的CGRect.我发现我必须将CGRect从UIScreen对象转换为UIWindow对象,并从UIWindow对象转换为UIView对象:

NSValue * keyboardEndFrame;
CGRect    screenRect;
CGRect    windowRect;
CGRect    viewRect;

// determine's keyboard height
screenRect    = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
windowRect    = [self.view.window convertRect:screenRect fromWindow:nil];
viewRect      = [self.view        convertRect:windowRect fromView:nil];
Run Code Online (Sandbox Code Playgroud)

我使用上面的内容来调整根视图的大小,使其不被键盘隐藏:

NSTimeInterval  duration;
CGRect          frame;

// determine length of animation
duration  = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

// resize the view
frame              = self.view.frame;
frame.size.height -= viewRect.size.height;

// animate view resize with the keyboard movement
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:duration];
self.view.frame = frame;
[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)